【发布时间】:2014-08-31 19:01:30
【问题描述】:
我有一个 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 并在运行应用程序时中断(而不是在编译时)。我试图将 onClickListener 设置为“onCreateView”、“onStart”、“onResume”、“onActivityCreated”等,但无处可去。有什么想法吗?
谢谢你,最好的!
编辑:我正在添加一些人们问我的东西。
打破的布局是一种叫做“随便”的布局;它是一个tablelayout,每个tablerow 上有8 个tablerows 和8 个imagebuttons(即一个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 中断,因为 a8 在findViewById 之后仍然设置为空。
【问题讨论】:
-
你能发布堆栈跟踪吗?
-
你可以发布布局吗?
-
你能把有问题的代码贴在
setOnClickListener()吗? -
该布局中很可能会丢失该对象(在 onClickListener 失败时),因此 v.findviewbyid 将为空,这发生在我身上很多次...
-
@Maaz 如果是这样,我会很高兴,但似乎并非如此!即使布局显示也很好,只是我无法访问图像按钮,所以我无法添加侦听器,但我看到了它们(实际上没有图片,因为我在我的 xml 上对它们进行了编程)
标签: android android-fragments android-fragmentactivity android-lifecycle android-inflate