我想要一个按钮点击关闭一个活动。我是新手,有点困惑。
这是ActivityOne
,它记录生命周期。
按下按钮,它会打开ActivityTwo
并将ActivityOne
置于后台
当我在onClickListener
:
Intent myIntent = new Intent(ActivityOne.this, ActivityTwo.class);
ActivityOne.this.startActivity(myIntent);
在ActivityTwo
我需要使用意图和finish()
方法来关闭活动。我试图谷歌它,我认为这可能会有效:
Intent myIntent2 = new Intent(getApplicationContext(), ActivityTwo.class);
ActivityTwo.this.finish(myIntent2);
完整的代码如下所示:
public class ActivityOne extends Activity {
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
// ...
Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO:
// Launch Activity Two
// Hint: use Context's startActivity() method
// Create an intent stating which Activity you would like to start
Intent myIntent = new Intent(ActivityOne.this, ActivityTwo.class);
// Launch the Activity using the intent
ActivityOne.this.startActivity(myIntent);
}
});
// ...
}
}
活动2:
public class ActivityTwo extends Activity {
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
// ...
Button closeButton = (Button) findViewById(R.id.bClose);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO:
// This function closes Activity Two
// Hint: use Context's finish() method
Intent myIntent2 = new Intent(getApplicationContext(), ActivityTwo.class);
ActivityTwo.this.finish(myIntent2);
}
});
// ...
}
}
答案 0 :(得分:45)
您想在点击按钮时关闭ActivityTwo
?只需使用finish();
ActivityTwo
中按钮侦听器的完整代码为:
Button closeButton = (Button) findViewById(R.id.bClose);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO:
// This function closes Activity Two
// Hint: use Context's finish() method
finish();
}
});
答案 1 :(得分:7)
@Arjun Krishnan你想杀死activity2吗?
试试这个
ActivityTwo.this.finish();
它会帮助你
答案 2 :(得分:4)
完成 当前活动 的最佳方法是使用finish()
方法。因此,在onClick()
按钮的ActivityTwo
内,您可以执行此操作。
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
//closes ActivityTwo
}
});
无需为完成当前活动制定新意图。另请注意,按下也将完成您的活动。
答案 3 :(得分:1)
替换这两行
Intent myIntent2=new Intent(getApplicationContext(),ActivityTwo.class);
ActivityTwo.this.finish(myIntent2);
使用此
ActivityTwo.this.finish();
答案 4 :(得分:1)
Button exit= (Button) findViewById(R.id.yes);
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity.this.finish();
}
});