Skip to content Skip to sidebar Skip to footer

Android Viewpager Findviewbyid Not Working - Always Returning Null

public class HSPTabletTestActivity extends Activity { private class MyPagerAdapter extends PagerAdapter { public int getCount() { return 2; } public Object in

Solution 1:

After much frustration and pulling my hair out over this issue, I have solved it! At least for me. Assuming you used the tutsplus tutorial like I did, you have separate XML files for your screens. Now, I assume those layout XMLs contain layouts within them (ie. LinearLayout, RelativeLayout, etc.). Now, those layouts contain your button and other widgets. What you have to do to be able to findViewById is, in the actual switch statement in the instatiateItem method, initialize your button in this way:

public Object instantiateItem(View collection, int position) {

    LayoutInflaterinflater= (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    intresId=0;
    switch (position) {
    case0:
        resId = R.layout.lighttab;
        Viewview= inflater.inflate(resId, null);
        RelativeLayout layout=(RelativeLayout)view.findViewById(R.id.relLayout);
        Button button=(Button)layout.findViewById(R.id.button);
        ((ViewPager) collection).addView(view, 0);
        return view;
    case1:
        resId = R.layout.securitytab;
        ...
        ...
        return view;
    }
}

So...first you have to inflate the view, then initialize the layout held within the view by casting the type of layout (RelativeLayout) and calling .findViewById(resource id). Then, you initialize the actual widget you're looking for by doing the same, but casting the widget type (Button) and calling .findViewById(resource id).

This worked for me, so I hope this saves you some trouble! Took forever for me to figure out.

Solution 2:

Just guess as you don't show xml for inflated. Do you use +@id. If not give it a try.

Solution 3:

You can avoid all this dirty job just adding setContentView(R.layout.youlayout) before findViewById

Post a Comment for "Android Viewpager Findviewbyid Not Working - Always Returning Null"