我有一个称为“活动”的活动,当通过setContentView()方法单击按钮时,该活动在View1和View2之间切换。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
}
我想在按下设备上的BackButton时切换到View1。
public void onBackPressed(){
View currentView = this.findViewById(R.layout.product_list);
if(currentView == findViewById(R.layout.category_list)){
Log.i("VIEW1", "BACKBUTTON CLICKED ON VIEW1");
} else if(currentView == findViewById(R.layout.product_list)) {
Log.i("VIEW2", "BACKBUTTON CLICKED ON VIEW2");
}
}
每当我单击view2上的后退按钮时,都会触发view1的if语句。当我将其分配给view2时,currentView变为view1。为什么会这样?
public void onClick(View view) {
setContentView(R.layout.product_list);
}
答案 0 :(得分:0)
在类级别声明View currentView
在onCreate中设置值
currentView = this.findViewById(R.layout.category_list);
然后
public void onBackPressed(){;
if(currentView == findViewById(R.layout.category_list)){
Log.i("VIEW1", "BACKBUTTON CLICKED ON VIEW1");
currentView = this.findViewById(R.layout.product_list);
} else {
Log.i("VIEW2", "BACKBUTTON CLICKED ON VIEW2");
currentView = this.findViewById(R.layout.category_list);
}
}
祝你好运