私は viewPager を使用しており、それにフラグメントを追加したいと考えています:
public class MyFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup contner,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_frag2_layout, container, false);
return view;
}
public static Fragment newInstance() {
// TODO Auto-generated method stub
MyFragment mfg = new MyFragment();
return mfg;
}
}
マイ PagerAdapter:
public class ViewPagerAdapter extends PagerAdapter
{
private static String[] titles = new String[]
{
"Page 1",
"Page 2",
"Page 3",
"Page 4"
};
private final Context context;
public ViewPagerAdapter( Context context )
{
this.context = context;
}
@Override
public String getPageTitle( int position )
{
return titles[ position ];
}
@Override
public int getCount()
{
return titles.length;
}
@Override
public Object instantiateItem( View pager, int position )
{
TextView v = new TextView( context );
v.setText( titles[ position ] );
((ViewPager)pager).addView( v, 0 );
//This gives me nullPointerException///////////////////////////////////
MyFragment mfg = new MyFragment();
((ViewPager)pager).addView(mfg.newInstance().getView());
return v;
}
@Override
public void destroyItem( View pager, int position, Object view )
{
((ViewPager)pager).removeView( (TextView)view );
}
@Override
public boolean isViewFromObject( View view, Object object )
{
return view.equals( object );
}
@Override
public void finishUpdate( View view ) {}
@Override
public void restoreState( Parcelable p, ClassLoader c ) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate( View view ) {}
}
MyFragment を ViewPager に追加する正しい方法は何ですか? ビューとして追加する必要があるため、newInstance() メソッドを使用しますが、nullPointerException が発生します。
ありがとう!