如果全局数据结构不存在(我在public class Globals extends Application
中是静态的),我想在我的一个活动中隐藏一个按钮。由于我想在每次恢复活动时重新绘制按钮,但是不想重绘视图的其余部分,我将视图的初始化放在onCreate()
中,并将按钮隐藏代码放在onResume()
中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myActivity);
}
@Override
protected void onResume() {
super.onResume();
if (Globals.datastructure == null) {
((Button) findViewById(R.id.myButton)).setVisibility(View.GONE);
}
}
当我分配数据结构然后从其他活动返回活动时,onResume
会正确执行,但按钮不会重新出现。
答案 0 :(得分:3)
包含该按钮的活动可能未被重新创建,这意味着当您从其他某个活动返回该活动时,该按钮永远不会被设置(返回)为可见。您应该将onResume()
更改为:
@Override
protected void onResume() {
super.onResume();
findViewById(R.id.myButton).setVisibility(Globals.datastructure == null ? View.GONE : View.VISIBLE);
}
所以基本上你只需要确保在Globals.datastructure != null
时,你也可以适当地改变可见性。换句话说:else
需要if
。