ViewPager +片段-片段未显示 [英] ViewPager + Fragments - Fragment not shown

查看:66
本文介绍了ViewPager +片段-片段未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用viewpager显示多个片段。目前,我只有一个片段,但似乎从未实例化。我尝试使用pager.setCurrentItem(0),但是从不调用适配器中的getItem方法。有人在下面的代码中看到为什么我的片段未加载吗?

I am trying to use a viewpager to display several fragments. At the moment I only have a single fragment but it appears that it is never being instantiated. I tried using pager.setCurrentItem(0) but the getItem method in the adapter is never being called. Does anyone see why my fragment is not loading in the below code?

主要活动

public class MainActivity extends SherlockFragmentActivity {

MyPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );

    // Create the FragmentPager Adapter and assign it to the viewpager
    adapter = new MyPagerAdapter( getSupportFragmentManager(), this );
    ViewPager pager = ( ViewPager ) findViewById( R.id.pager );
    pager.setAdapter( adapter );
    pager.setCurrentItem( 0 );

    // Setup the tab page indicator
    TabPageIndicator indicator = ( TabPageIndicator ) findViewById( R.id.indicator );
    indicator.setViewPager( pager );
}

class MyPagerAdapter extends FragmentStatePagerAdapter {
    private SparseArray<Fragment> fragmentPageMap;

    public MyPagerAdapter(FragmentManager fm, Activity context) {
        super( fm );
        fragmentPageMap = new SparseArray<Fragment>();
    }

    @Override
    public Fragment getItem(int index) {
        switch ( index ) {
        case 0:
            if ( fragmentPageMap.get( index ) != null ) {
                SherlockListFragment scheduleFragment =  ScheduleListFragment.newInstance();
                fragmentPageMap.put( index, scheduleFragment );
                return scheduleFragment;
            } else {
                return fragmentPageMap.get( index );
            }
        default:
            return null;
        }
    }

    /*@Override
    public void destroyItem(View container, int index, Object object) {
        super.destroyItem( container, index, object );
        fragmentPageMap.remove( index );
    }*/

    @Override
    public CharSequence getPageTitle(int index) {
        return ( ( ViewPagerPage ) fragmentPageMap.get( index ) ).getTitle();
    }

    @Override
    public int getCount() {
        return fragmentPageMap.size();
    }
}

public interface ViewPagerPage {
    String getTitle();
}

MainActivity布局

MainActivity Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<com.viewpagerindicator.TabPageIndicator
    android:id="@+id/indicator"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold" />

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

</LinearLayout>

ScheduleListFragment

ScheduleListFragment

public class ScheduleListFragment extends SherlockListFragment implements ViewPagerPage {

private ScheduleAdapter adapter;
private final String TITLE = "Schedule";

public static ScheduleListFragment newInstance() {
    ScheduleListFragment newFrag = new ScheduleListFragment();
    Bundle args = new Bundle();
    newFrag.setArguments( args );
    return newFrag;
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate( R.layout.fragment_schedule_list, null );
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate( R.menu.fragment_schedule_list, menu );
}

// Container Activity must implement this interface
public interface OnAddItemClickedListener {
    public void onAddItemClicked();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch ( item.getItemId() ) {
    case R.id.add_item:
        Intent myIntent = new Intent( getActivity(), AddScheduleItemActivity.class );
        startActivityForResult( myIntent, 1 );

        return true;
    default:
        return super.onOptionsItemSelected( item );
    }
}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated( savedInstanceState );
    setHasOptionsMenu( true );

    adapter = new ScheduleAdapter( getActivity() );

    setListAdapter( adapter );
}

private class SampleItem {
    public String tag;
    public int iconRes;

    public SampleItem(String tag, int iconRes) {
        this.tag = tag;
        this.iconRes = iconRes;
    }
}

public class ScheduleAdapter extends ArrayAdapter<SampleItem> {

    public ScheduleAdapter(Context context) {
        super( context, 0 );
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        if ( convertView == null ) {
            convertView = LayoutInflater.from( getContext() ).inflate( R.layout.results_list_row, null );
        }
        ImageView icon = ( ImageView ) convertView.findViewById( R.id.row_icon );
        icon.setImageResource( getItem( position ).iconRes );
        TextView title = ( TextView ) convertView.findViewById( R.id.row_title );
        title.setText( getItem( position ).tag );

        return convertView;
    }

}

@Override
public String getTitle() {
    return TITLE;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ( resultCode == android.app.Activity.RESULT_OK ) {
        String name = ( String ) data.getExtras().get( "TEXT" );
        Toast.makeText( getActivity(), name, Toast.LENGTH_LONG ).show();
    }
}

片段布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

谢谢,
Nathan

Thanks, Nathan

当前解决方案:

更改了适配器的构造函数,以初始化第一个片段并将其添加到内部映射中。是否有人认为这样做有什么问题,或者是否有改进上述任何代码的方法?

Changed the adapters constructor to initialize the first fragment and add it to the internal map. Does anyone see anything wrong with doing this, or a way to improve any of the code posted above? Thanks!

public MyPagerAdapter(FragmentManager fm, Activity context) {
        super( fm );
        fragmentPageMap = new SparseArray<Fragment>();
        SherlockListFragment scheduleFragment = ScheduleListFragment.newInstance();
        fragmentPageMap.put( 0, scheduleFragment );
    }


推荐答案

getCount() MyPagerAdapter 中返回0,因此将不创建任何片段,它应返回 N 如果要实例化 N 片段。

getCount() is returning 0 in MyPagerAdapter so no Fragment will be created, it should return N if you want N Fragments to be instantiated.

fragmentPageMap 在构造函数中创建,当 getCount()被调用,而 getCount() getItem(index)之前被调用,这就是为什么 getCount()返回0

fragmentPageMap is created in the constructor and is empty when getCount() is called and getCount() is called before getItem(index), that is why getCount() returns 0

在这种情况下,您不需要开关,因为您每次都实例化相同的Fragment。但是,如果您要实例化不同的片段,则将需要它。

In this case you don't need a switch because you are instantiating the same Fragment each time. But you would need it if you where instantiating diferent Fragments.

@Override
public Fragment getItem(int index) {
  switch (index) {
    case 0:
      return new Fragment1();
    case 1:
      return new Fragment2();
  }
  return null;
}

这篇关于ViewPager +片段-片段未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆