我正在尝试让我的应用程序使用3个类显示另一个活动:
MainActivity
- 主屏幕ActivityOne
- 第二个屏幕ButtonListener
- onClickListener
我的ActivityMain
代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
ButtonListener buttonListener = new ButtonListener();
button.setOnClickListener(buttonListener);
}
}
我的ActivityOne
代码:
public class ActivityOne extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_one);
}
}
我的ButtonListener
代码:
public class ButtonListener implements View.OnClickListener {
public ButtonListener() {}
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, ActivityOne.class);
startActivity(intent);
}
}
答案 0 :(得分:0)
调整ButtonListener
以维持对MainActivity
的引用:
public class ButtonListener implements View.OnClickListener {
MainActivity activity;
public ButtonListener(MainActivity activity) {
this.activity = activity;
}
@Override
public void onClick(View view) {
Intent intent = new Intent(activity, ActivityOne.class);
activity.startActivity(intent);
}
}
然后在onCreate()
的{{1}}中,以这种方式创建MainActivity
的实例:
ButtonListener