Issue
I have an Activity which has a fragment. This fragment is changing it's layout depending on what's going on, for instance:
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;
}
I am changing the nLesson and nPage values as convenied and then using
activity.getFragmentManager().beginTransaction()
.detach(instance)
.attach(instance)
.commit();
I am refreshing it.
However, in one of those layouts I have some views I want to work with. I am trying to set a onClickListener on one of the views but it always displays a nullPointerException and breaks when running the app (not in compiling time). I tried to set the onClickListener in "onCreateView", "onStart", "onResume", "onActivityCreated", etc. Nowhere worked. Any idea?
Thank you, best!
EDIT: I am adding some stuff that people asked me.
The layout that breaks is the one called "whatever"; It is a tablelayout with 8 tablerows and 8 imagebuttons on each tablerow (that is, a 8x8=64 squares, a chessboard). All the squares are set to null when I try to add the listener on them.
They all are similar to
<ImageButton
android:id="@+id/squareA8"
android:contentDescription="@string/r8c1"
android:layout_height="35dp"
android:layout_width="35dp"
android:tag="true"/>
This is the java code that breaks:
public void doIt()
{
chessHandler = new ChessHandler(cActivity);
chessHandler.initialize();
}
chessHandler is a class from my own, won't post it because it is irrelevant for this case. This is the part of the code interesting:
a8 = (ImageButton)activity.findViewById(R.id.squareA8);
a8.setOnClickListener(new on_click(a8, a,8));
There are 64 lines as these ones, the setOnClickListener breaks because a8 is still set as null after the findViewById.
Solution
a8 = (ImageButton)activity.findViewById(R.id.squareA8);
a8.setOnClickListener(new on_click(a8, a,8));
In a typical onCreateView(), call findViewById() on the view you just inflated, not the activity. You haven't yet returned the view to the framework and it isn't part of the activity view hierarchy, so any child views cannot be found in the activity.
Answered By - laalto
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.