我正面临一个奇怪的问题,我正在尝试使用6种不同的布局实现一项活动,一次只能看到一种基于布局类型的活动,而其他布局会隐藏
因此,流程是一个处理程序,在20秒后显示每个类型/视图,然后说n次活动结束。
现在的问题是,如果我重新启动活动,我将无法看到任何视图
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout style="@style/RelParent"
android:id="@+id/rel_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<include
android:id="@+id/rel_1"
layout="@layout/layout_1"/>
<include
android:id="@+id/rel_2"
layout="@layout/layout_2"/>
<include
android:id="@+id/rel_3"
layout="@layout/layout_3"/>
<include
android:id="@+id/rel_4"
layout="@layout/layout_4"/>
<include
android:id="@+id/rel_5"
layout="@layout/layout_5"/>
<include
android:id="@+id/rel_6
layout="@layout/layout_6"/>
</RelativeLayout>
活动代码:
public class ExampleActivity extends AppCompatActivity {
private ArrayList<Model> mModels;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(null);
Log.d(TAG, "onCreate, starting quiz");
initLayoutTypeMap();
hideAllLayouts();
mModels = //getDataFromDB;
mHandler = new Handler();
mHandler.postDelayed(mRunnable, 2000);
}
private void initLayoutTypeMap() {
mTypeLayoutMap = new HashMap<>();
mTypeLayoutMap.put(type1, relType1);
mTypeLayoutMap.put(type2, relType2);
mTypeLayoutMap.put(type3, relType3);
mTypeLayoutMap.put(type4, relType4);
mTypeLayoutMap.put(type5, relType5);
mTypeLayoutMap.put(type6, relType6);
}
private void startNew(int id) {
Model model = mModels.get(id);
showLayout(model.getType);
showLayout(type);
//Do all the data showing on views
}
private void showLayout(String type) {
mTypeLayoutMap.get(type).setVisibility(View.VISIBLE);
}
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (id <= mModels.size()) {
hideAllLayouts();
clearAll();
startNew(id);
id++;
mHandler.postDelayed(mRunnable, 20000);
} else {
hideAllLayouts();
mHandler.removeCallbacks(mRunnable);
finish();
}
}
};
}
对于第一次迭代,一切都按预期工作。但是,一旦我完成此活动并尝试再次启动它,就看不到任何视图
答案 0 :(得分:1)
将处理程序代码从onResume()
移至onCreate()
,如
@Override
public void onResume(){
if(mTypeLayoutMap == null){
initLayoutTypeMap();
}
hideAllLayouts();
if(mModel == null){
mModels = //getDataFromDB;
}
if(mHandler == null){
mHandler = new Handler();
}
mHandler.postDelayed(mRunnable, 2000);
}
并在finish()
之前声明你的id = 1,所以它会再次迭代。
else {
hideAllLayouts();
id=1;
mHandler.removeCallbacks(mRunnable);
finish();
}