我在 android 中使用 Master Detail Flow 模板。我想在应用程序启动时以编程方式访问列表中的项目,以便设置那里的 TextViews 的字体大小和颜色。如果我在 onResume(ItemListActivity 或 ItemListFragment)中编码,ListView 不为空,但 3 个 TextView(ListView 的子项)为空。
public void updateActivity( )
{
ViewGroup leftPane = ( ViewGroup ) findViewById( R.id.item_list );
FrameLayout frameLayout = ( FrameLayout ) leftPane.getChildAt( 0 );
FrameLayout frameLayout2 = ( FrameLayout ) frameLayout.getChildAt( 1 );
ListView listView = ( ListView ) frameLayout2.getChildAt( 1 ); // listView NOT null
TextView item0 = ( TextView ) listView.getChildAt( 0 ); // item0 is NULL !!!!!
}
我在 ItemListActivity 中提出了这段代码作为(脏)修复,我不确定它是否会一直工作并且与设备无关:
public View onCreateView( String name, Context context, AttributeSet attrs )
{
// started is an int instance variable, initialized at 0
Log.w( "MA", "Inside Activity:onCreateView, started = " + started );
// if started <= 40 ==> item0 is NULL inside updateActivity
if( started == 41) // ==> item0 NOT null inside updateActivity
updateActivity( );
started++;
return super.onCreateView( name, context, attrs );
}
那行得通,但我正在寻找(很多)更好的解决方案;这是 LogCat 中的输出(它确实在 48 处停止):
所涉及的各种生命周期方法似乎有一些交错执行。必须有一种方法在方法内部进行编码,以保证在该方法执行之前已实例化所有视图;我试图从 Activity、FragmentActivity、ListFragment 和 Fragment 类中重写很多方法;到目前为止没有运气,TextViews(ListView 的子项)在所有这些方法中都是 NULL。顺便说一句,当启动等于 41 时,其他 TextViews 仍然为 NULL,当启动等于 43 时,第二个变为 NOT null,当启动等于 45 时,第三个变为 NOT null。知道吗?感谢您的任何帮助。
......
05-16 19:27:36.460: W/MA(3155): Inside Activity:onCreateView, started = 37
05-16 19:27:36.460: W/MA(3155): Inside Activity:onCreateView, started = 38
05-16 19:27:36.460: W/MA(3155): Inside ItemListActivity:onResume
05-16 19:27:36.460: W/MA(3155): Inside ItemListFragment:onResume
05-16 19:27:36.484: W/MA(3155): Inside Activity:onCreateView, started = 39
05-16 19:27:36.484: W/MA(3155): Inside Activity:onCreateView, started = 40
05-16 19:27:36.632: W/MA(3155): Inside Activity:onCreateView, started = 41
05-16 19:27:36.632: W/MA(3155): Inside checkActivity
05-16 19:27:36.632: W/MA(3155): Inside Activity:onCreateView, started = 42
05-16 19:27:36.640: W/MA(3155): Inside Activity:onCreateView, started = 43
05-16 19:27:36.640: W/MA(3155): Inside Activity:onCreateView, started = 44
05-16 19:27:36.648: W/MA(3155): Inside Activity:onCreateView, started = 45
05-16 19:27:36.656: W/MA(3155): Inside Activity:onCreateView, started = 46
05-16 19:27:36.742: W/MA(3155): Inside Activity:onCreateView, started = 47
05-16 19:27:36.742: W/MA(3155): Inside Activity:onCreateView, started = 48