[英]android process crash on adb with simple app, not sure what i'm doing wrong
package com.russell.saw;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class learnandroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button landroid_button = (Button) findViewById(R.id.landroid_button); {
landroid_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.button);
}
});
}
Button back_button = (Button) findViewById(R.id.back_button); {
back_button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
setContentView(R.layout.main);
}
});
}
}
}
我不确定出什么问题了,它只是一个简单的学习测试仪应用程序,带有两个按钮,从一页到另一页,但是一旦在手机上运行它,我就会崩溃。
哇! 您的onClickListeners设置有误。 您正在setContentView
中调用setContentView
。 相反,您需要使用一种意图从一个活动转到下一个活动。 它需要看起来像这样:
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Main.this, MyOtherActivity.class);
startActivity(intent);
}
});
另外,不要使用landroid_button
来引用您的按钮:这只是资源的XML ID。 相反,您需要通过执行以下操作来抓住按钮:
Button myLandroidButton = (Button)findViewById(R.id.landroid_button)
然后,当您设置myLandroidButton
,请使用该变量: myLandroidButton
例如myLandroidButton.setOnClickListener
等。
如果您尚未向AndroidManifest.xml添加活动标签,则需要这样做:
<activity android:name="learnandroid" android:label="I am learning Android"></activity>
您需要针对每个活动(在应用程序标签下方)执行此操作。
尽管我怀疑这会导致崩溃,但是您的代码存在严重问题。 当您在侦听器的onClick
内部调用setContentView
,按钮landroid_button和back_button不再有效。 也就是说,它们是不再绑定到窗口的对象。 (如果新的内容视图具有“相同”按钮,则它们将不再具有侦听器。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.