我有一个有片段的Activity。这个片段正在改变它的布局,具体取决于发生的事情,例如:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = null;
switch(nLesson)
{
case 1:
switch(nPage)
{
case 0: v = inflater.inflate(R.layout.lesson, container, false);
break;
case 1: v = inflater.inflate(R.layout.basic, container, false);
break;
case 2: v = inflater.inflate(R.layout.whatever, container, false);
doIt();
break;
case 3: v = inflater.inflate(R.layout.lesso, container, false); break;
}
break;
}
return v;
}
我正在更改nLesson和nPage值,然后使用
activity.getFragmentManager().beginTransaction()
.detach(instance)
.attach(instance)
.commit();
我很清醒。
但是,在其中一个布局中,我有一些我想要使用的视图。我试图在其中一个视图上设置onClickListener,但它总是显示nullPointerException并在运行应用程序时中断(不在编译时)。我尝试在“onCreateView
”,“onStart
”,“onResume
”,“onActivityCreated
”等设置onClickListener。无处可行。有什么想法吗?
谢谢,最好!
编辑:我正在添加人们问我的一些内容。
打破的布局是一个叫做“无论什么”的布局;它是tablelayout
,每个tablerows
有8 imagebuttons
和8 tablerow
(即8x8 = 64个方块,棋盘)。当我尝试在它们上添加侦听器时,所有方块都设置为null。
它们都与
类似<ImageButton
android:id="@+id/squareA8"
android:contentDescription="@string/r8c1"
android:layout_height="35dp"
android:layout_width="35dp"
android:tag="true"/>
这是破解的java代码:
public void doIt()
{
chessHandler = new ChessHandler(cActivity);
chessHandler.initialize();
}
chessHandler是我自己的一个类,不会发布它,因为它与这种情况无关。这是代码中有趣的部分:
a8 = (ImageButton)activity.findViewById(R.id.squareA8);
a8.setOnClickListener(new on_click(a8, a,8));
这些行有64行,setOnClickListener
会中断,因为在findViewById
之后a8仍然设为null。
答案 0 :(得分:1)
a8 = (ImageButton)activity.findViewById(R.id.squareA8);
a8.setOnClickListener(new on_click(a8, a,8));
在典型的onCreateView()
中,请在您刚刚虚张的视图上调用findViewById()
,而不是activity
。您还没有将视图返回到框架,它不是活动视图层次结构的一部分,因此在活动中找不到任何子视图。