如何在方法instantiateItem上实例化片段?

时间:2015-06-16 13:47:31

标签: android android-layout android-fragments

我对Android编程非常陌生,我正试图在instantiateItem类上创建SlidingTabsBasicFragment,以返回ConversationsFragment的片段。

根据我的理解,我的类ConversationsFragment返回一个片段,它将被实例化。但相反,第二页上没有显示任何内容。

我正在使用SlidingTabsBasic示例进行此操作:

主要活动onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.v("Logs", "first");

    if (savedInstanceState == null) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
        transaction.replace(R.id.sample_content_fragment, fragment);
        //ConversationsFragment fragment = new ConversationsFragment();
        //transaction.replace(R.id.sample_content_fragment, new ConversationsFragment());
        transaction.commit();
    }
}

SlidingTabsBasicFragment:

package com.example.android.slidingtabsbasic;

import com.example.android.common.logger.Log;
import com.example.android.common.view.SlidingTabLayout;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.TextView;


/**
 * A basic sample which shows how to use {@link com.example.android.common.view.SlidingTabLayout}
 * to display a custom {@link ViewPager} title strip which gives continuous feedback to the user
 * when scrolling.
 */
public class SlidingTabsBasicFragment extends Fragment {

    static final String LOG_TAG = "SlidingTabsBasicFragment";

    /**
     * A custom {@link ViewPager} title strip which looks much like Tabs present in Android v4.0 and
     * above, but is designed to give continuous feedback to the user when scrolling.
     */
    private SlidingTabLayout mSlidingTabLayout;

    /**
     * A {@link ViewPager} which will be used in conjunction with the {@link SlidingTabLayout} above.
     */
    private ViewPager mViewPager;

    /**
     * Inflates the {@link View} which will be displayed by this {@link Fragment}, from the app's
     * resources.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sample, container, false);
    }

    // BEGIN_INCLUDE (fragment_onviewcreated)
    /**
     * This is called after the {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)} has finished.
     * Here we can pick out the {@link View}s we need to configure from the content view.
     *
     * We set the {@link ViewPager}'s adapter to be an instance of {@link SamplePagerAdapter}. The
     * {@link SlidingTabLayout} is then given the {@link ViewPager} so that it can populate itself.
     *
     * @param view View created in {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
     */
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // BEGIN_INCLUDE (setup_viewpager)
        // Get the ViewPager and set it's PagerAdapter so that it can display items
        mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        mViewPager.setAdapter(new CustomPagerAdapter(getFragmentManager(),getActivity()));
        // END_INCLUDE (setup_viewpager)

        // BEGIN_INCLUDE (setup_slidingtablayout)
        // Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
        // it's PagerAdapter set.
        mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setViewPager(mViewPager);
        // END_INCLUDE (setup_slidingtablayout)
    }
    // END_INCLUDE (fragment_onviewcreated)


    public class CustomPagerAdapter extends FragmentPagerAdapter {

        protected Context mContext;

        public CustomPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            mContext = context;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "Item " + (position + 1);
        }

        @Override
        public Fragment getItem(int position) {

            if(position==0){
                // return fragment
            }else{
                ConversationsFragment fragment = new ConversationsFragment();
                return fragment;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }
    }


}

这是我的ConversationsFragment:

public class ConversationsFragment extends Fragment implements AbsListView.OnItemClickListener {

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

/**
 * The fragment's ListView/GridView.
 */
private AbsListView mListView;

/**
 * The Adapter which will be used to populate the ListView/GridView with
 * Views.
 */
private List conversationsListItemList; // at the top of your fragment listW
private ListAdapter mAdapter;

// TODO: Rename and change types of parameters
public static ConversationsFragment newInstance(String param1, String param2) {
    ConversationsFragment fragment = new ConversationsFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ConversationsFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    // TODO: Change Adapter to display your content
    conversationsListItemList = new ArrayList();
    conversationsListItemList.add(new ConversationsListItem("Example 1","conversa"));
    conversationsListItemList.add(new ConversationsListItem("Example 2","conversa"));
    conversationsListItemList.add(new ConversationsListItem("Example 3","conversa"));
    mAdapter = new ConversationsListAdapter(getActivity(), conversationsListItemList);
   /* mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);*/
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_conversations, container, false);

    // Set the adapter
    mListView = (AbsListView) view.findViewById(android.R.id.list);
    ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

    // Set OnItemClickListener so we can be notified on item clicks
    mListView.setOnItemClickListener(this);

    return view;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (null != mListener) {
        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
    }
}

public void setEmptyText(CharSequence emptyText) {
    View emptyView = mListView.getEmptyView();

    if (emptyView instanceof TextView) {
        ((TextView) emptyView).setText(emptyText);
    }
}

public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(String id);
}

}

截图:

第一个屏幕:

https://goo.gl/photos/Ze5ThZgevGaALDj47

第二屏:

https://goo.gl/photos/x7JPnESAtZsBT5DC8

现在出现这个错误:

06-16 12:32:58.946  12228-12228/com.example.android.slidingtabsbasic E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.android.slidingtabsbasic, PID: 12228
    java.lang.NullPointerException
            at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:417)
            at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:412)
            at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)

1 个答案:

答案 0 :(得分:0)

我认为您的代码问题是返回ViewFragment

以下代码为我工作

public class CustomPagerAdapter extends FragmentPagerAdapter {

    protected Context mContext;

    public CustomPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        mContext = context;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "" + tabsTitle[position];
    }

    @Override
    public Fragment getItem(int position) {

         if(position==0){
           // return fragment
         }else{
         ConversationsFragment fragment = new ConversationsFragment();
                return fragment;
          }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }
}