只需触摸屏幕即可启动新活动
问题描述:
我试图启动一个全新的活动,当我触摸屏幕时将显示一个新的字符串。这是MainActivity代码。我的第一个活动显示一个“你好世界”,我的新活动应该只显示一个新的字符串。所有的资源文件和清单都是正确的。但是,该运行在onClick之后不断崩溃。任何帮助深表感谢。只需触摸屏幕即可启动新活动
package com.example.myfirsttest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
//Call the NewActivity from the MainActivity
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this,NewActivity.class);
startActivity(startIntent);
}
});
}
}
答
有一种更好的方式来做到这一点
package com.example.myfirsttest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity{
private static final String MESSAGE_TAG = "my_message";
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
Bundle extras = getIntent().getExtras();
String stringMessage = extras.getString(MESSAGE_TAG);
TextView message = (TextView) findViewById(R.id.message);
if(stringMessage != null && !stringMessage.isEmpty()) {
message.setText(stringMessage);
}
//Call the NewActivity from the MainActivity
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this,MainActivity.class);
startIntent.putExtra(MESSAGE_TAG, "hello second World");
startActivity(startIntent);
}
});
}
}
现在,你不必有此相同的任务2个注册活动是布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">
<TextView
android:id="@+id/message"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
编码快乐。
你可以发布你的logcat的崩溃吗? – apmartin1991 2014-08-29 20:11:17
粘贴您的logcat,以便我们看到错误消息 – 2014-08-29 20:11:19
您是否在Manifest上注册了NewActivity? – 2014-08-29 20:19:14