`

java.lang.RuntimeException: Unable to start activity ComponentInfo

阅读更多

      根据java的执行顺序有关!目前遇到的这个问题就是因为在系统运行开始的时候就已经调用父类的构造方法,接着调用setContentView方法展示视图界面。R.layout.main是R.java资源类中的一个属性。当你在调用这个方法之后在声明Widget就会报:java.lang.RuntimeException: Unable to start activity ComponentInfo错误

    错误原因

public class mainActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Button btn = (Button) this.findViewById(R.id.enter);
		btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(mainActivity.this,
						SecondActivity.class);
				startActivity(intent);
			}
		});
		setContentView(R.layout.main); //不该将其写在后面
	}
}

 

正确的做法是

public class mainActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button btn = (Button) this.findViewById(R.id.enter);
		btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(mainActivity.this,
						SecondActivity.class);
				startActivity(intent);
			}
		});

	}

  

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics