作为Android应用程序开发的新手,我试图学习使用Intent连接两个活动。我尝试了一本书中的代码。它总是抛出一个错误,说-MainActivity类和NewActivity类中已经定义了“ onCreate(Bundle)”。如果我能找到解决方案,那将有很大的帮助。
MainActivity.class
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this, NewActivity.class);
startActivity(startIntent);
}
});
}
NewActivity.class
public class NewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
}
}
最佳答案
如果要连接这些活动,则必须执行以下操作:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = getWindow().getDecorView().findViewById(android.R.id.content);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent startIntent = new Intent(MainActivity.this, NewActivity.class);
startActivity(startIntent);
}
});
}
然后在第二个活动中,只需删除:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_new);
}
并复制此:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
}
它将起作用。