在android中,有三个活动。我可以使用下一个按钮转到每个活动,但是当使用上一个按钮从第二个活动返回到第一个活动时,它不会响应上一个按钮。 我的三个.java文件是 1. MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Next = (Button) findViewById(R.id.button1);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), DisplayMessageActivity.class);
startActivityForResult(myIntent, 0);
}
});
}
}
DisplayMessageActivity.java
public class DisplayMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Button pre = (Button) findViewById(R.id.button2);
pre.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
}
});
setContentView(R.layout.activity_display_message);
Button Next = (Button) findViewById(R.id.button3);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), ThirdActivity.class);
startActivityForResult(myIntent, 0);
}
});
}
}
ThirdActivity.java
public class ThirdActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_activity);
Button previous = (Button) findViewById(R.id.button4);
previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
}
答案 0 :(得分:0)
首先,java变量应该从小写字母开始,如果它不是常量变量(参见Variables Java Documentation)。
要解决您的问题,您应该在finish()
setResult(RESULT_OK, intent)
之后致电DisplayMessageActivity.java
。同时删除setContentView(R.layout.activity_display_message)
的第二次调用。
public class DisplayMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Button pre = (Button) findViewById(R.id.button2);
pre.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish(); //add this
}
});
//setContentView(R.layout.activity_display_message);//remove this
Button next = (Button) findViewById(R.id.button3);//rename 'Next' to 'next'
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), ThirdActivity.class);
startActivityForResult(myIntent, 0);
}
});
}
}