向LinearLayout添加TextView无效:生命周期状态无法逐行显示
问题解决:ScrollView中状态日志被覆盖而非新增的问题
嘿,我一眼就揪出问题啦!你在onResume、onPause这些生命周期方法里,重复调用了setContentView(R.layout.activity_lifecycle)——这会让系统重新加载整个布局文件,把之前添加到LinearLayout里的所有TextView全部清空,所以每次状态变化看起来都是“覆盖”,而不是一行行累加。
修复要点:
- 只在
onCreate里调用一次setContentView:其他生命周期方法不需要重新加载布局,否则会直接重置整个界面 - 提前复用LinearLayout引用:在
onCreate里就找到linear实例并保存为全局引用,后续直接使用,不用每次都findViewById
修改后的完整代码:
int numc= 0; int nums= 0; int numr= 0; int nump= 0; int numst=0; int numd= 0; TextView numCreate; TextView numStart; TextView numResume; TextView numPause; TextView numStop; TextView numDestroy; TextView tCreate; TextView tStart; TextView tResume; TextView tPause; TextView tStop; TextView tDestroy; LinearLayout linear; // 全局保存LinearLayout引用 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lifecycle); // 仅在这里调用一次布局加载 numc++; Log.d("STATE", "onCreate executed"); displayCount(); // 初始化LinearLayout,后续直接复用 linear= findViewById(R.id.linearLay); TextView t1= new TextView(this); t1.setText("onCreate executed"); linear.addView(t1); } @Override public void onResume() { super.onResume(); // 移除此处的setContentView,避免重置布局 numr++; Log.d("STATE", "onRes executed" + numr); displayCount(); // 直接用全局的linear添加新日志 TextView t2= new TextView(this); t2.setText("onResume executed"); linear.addView(t2); } @Override public void onPause() { super.onPause(); // 移除此处的setContentView,避免重置布局 nump++; Log.d("STATE", "onPause executed" + nump); displayCount(); // 直接用全局的linear添加新日志 TextView t3= new TextView(this); t3.setText("onPause executed"); linear.addView(t3); Log.d("INCREMENT", String.valueOf(linear.getChildCount())); }
这样修改后,每次状态变化时,新的状态日志TextView都会被追加到LinearLayout中,不会再被重置,你就能看到一行行累加的状态记录啦!
内容的提问来源于stack exchange,提问作者Alex Espiritu
相关产品推荐
相关产品推荐

