我如何使用FragmentTransaction的replace()替换为ListFragment?

时间:2015-02-19 13:07:43

标签: android replace android-tabhost fragmenttransaction

此类包含我想要显示ListFragment的联系人选项卡的onclick选项卡     SecondFragment.java

package com.example.crush_crm;
import android.app.ListFragment;
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.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;

public class SecondFragment extends Fragment implements OnTabChangeListener {

    Fragment fragment;

    private View mRoot;
    private int mCurrentTab;
    ListFragment listfragment;
    public static final String TAG = SecondFragment.class.getSimpleName();
    public static SecondFragment newInstance() {
        return new SecondFragment();
    }


    private TabHost Tabhost;
    FragmentManager fm = getFragmentManager();

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);
        listfragment=new MyListFragment();

        Tabhost.setOnTabChangedListener(this);
        Tabhost.setCurrentTab(mCurrentTab);
        // manually start loading stuff in the first tab
        updateTab("Contact", R.id.tab1);
    }
    private void updateTab(String tabId, int placeholder) {
        FragmentManager fm = getFragmentManager();
        if (fm.findFragmentByTag(tabId) == null) {
            fm.beginTransaction()
            .replace(placeholder, new MyListFragment(), tabId)
            .commit();

        }
        if(tabId=="Contacts"){
            fm.beginTransaction()
                    .replace(placeholder,new MyListFragment(), tabId)
                    .commit();
            }
            if(tabId=="Delete"){
                fm.beginTransaction()
                        .replace(placeholder, new DeleteFragment(), tabId)
                        .commit();
                }
            if(tabId=="Edit"){
                fm.beginTransaction()
                        .replace(placeholder, new EditFragment(), tabId)
                        .commit();
                }

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.d("Hiii","i m in bottomFrag3.5");

        mCurrentTab=0;

        mRoot = inflater.inflate(R.layout.main, null);
        Tabhost=(TabHost) mRoot.findViewById(R.id.tabHost);
        Tabhost.setup();

        TabSpec spec1=Tabhost.newTabSpec("Contacts");
        spec1.setContent(R.id.tab1);
        spec1.setIndicator(getTabIndicator(Tabhost.getContext(), R.string.tab_title_1,R.drawable.contact));

        TabSpec spec2=Tabhost.newTabSpec("Edit");
        spec2.setIndicator(getTabIndicator(Tabhost.getContext(), R.string.tab_title_1,R.drawable.edit));
        spec2.setContent(R.id.tab2);


        TabSpec spec3=Tabhost.newTabSpec("Delete");
        spec3.setIndicator(getTabIndicator(Tabhost.getContext(), R.string.tab_title_1,R.drawable.delete));
        spec3.setContent(R.id.tab3);


        Tabhost.addTab(spec1);
        Tabhost.addTab(spec2);
        Tabhost.addTab(spec3);

        Tabhost.setOnTabChangedListener(this);
        Tabhost.setCurrentTab(mCurrentTab);

        return mRoot;


    }


    private View getTabIndicator(Context context, int title, int icon) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
        ImageView iv = (ImageView) view.findViewById(R.id.imageView);
        iv.setImageResource(icon);
        return view;
    }

    @Override
    public void onTabChanged(String tabId) {

        switch (Tabhost.getCurrentTab()) {
        case 0:
            //FragmentTransaction ft = fm.beginTransaction();
            Log.d("Hey","Fragment Transaction");
            //fm.beginTransaction().replace(R.id.tab1, new ContactFragment(),tabId);
            //ft.commit();
            Log.d(TAG, "onTabChanged(): tabId=" + tabId);
            updateTab(tabId, R.id.tab1);
            mCurrentTab=0;
            break;
        case 1:
            //do what you want when tab 1 is selected
            Log.d("Hey","Fragment Transaction2");
            Log.d(TAG, "onTabChanged(): tabId=" + tabId);
            updateTab(tabId, R.id.tab2);
            mCurrentTab=1;
            break;
        case 2:
            //do what you want when tab 2 is selected
            Log.d("Hey","Fragment Transaction3");
            Log.d(TAG, "onTabChanged(): tabId=" + tabId);
            updateTab(tabId, R.id.tab3);
            mCurrentTab=2;
            break;

        default:

            break;

        }



    }
}

这是扩展ListFragment的类,可以通过单击第一个选项卡“Contacts”来显示List中的联系人

MyListFragment.java
package com.example.crush_crm;
import java.util.ArrayList;
import java.util.List;





import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyListFragment extends ListFragment implements OnItemClickListener, OnCloseListener,LoaderCallbacks<Cursor>{

    String[] nameInput=new String[]{"hi"};
    String[] orgInput=new String[]{"how"};
    String [] id;

    ArrayList<String> nameList = new ArrayList<String>();
    ArrayList<String> orgList = new ArrayList<String>();
    CustomAdapter adapter;
    private List<RowItem> rowItems;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.d("OnCreateview","hi");
        return inflater.inflate(R.layout.list_fragment, null, false);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        Log.d("OnActivityCreated","hi");
        Context context = getActivity();
        MySQLiteHelper db = new MySQLiteHelper(context);
        //db.addContact(new CRMCONTACT("415"));
        //db.addContact(new CRMCONTACT("445"));
        id=db.selectContact();


        Bundle myBundle = new Bundle();
        myBundle.putStringArray("ID", id);
        getLoaderManager().initLoader(0, myBundle, this);


        //String id="1";

        // db.addContact(new CRMCONTACT("1"));
        /*   String[] id=db.selectContact();
        for(String id1 : id)
        {
            //ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
            Log.d("Hi","ContentResolver");
/*          String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
            String[] orgWhereParams = new String[]{id1,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}; 
            Cursor orgCur = getActivity().getContentResolver().query(ContactsContract.Data.CONTENT_URI,null, orgWhere, orgWhereParams, null);
            Log.d("Hi","cursor1");
            orgCur.moveToFirst();

                    Log.d("Hi","cursor");
                    String name1=orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DISPLAY_NAME));
                    String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                    String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                    Log.d("Name",name1);
                    Log.d("Org",orgName);
                    nameList.add(name1);
                    orgList.add(orgName);
                //Toast.makeText(this, name1+orgName, Toast.LENGTH_SHORT).show();
                Log.d("Org",orgName);

            orgCur.close();
        }

        nameInput = nameList.toArray(new String[nameList.size()]);
        orgInput=orgList.toArray(new String[orgList.size()]);

         */      
        for (int i = 0; i < nameList.size(); i++) {
            String strings = nameList.get(i);
            Log.d("Print",strings);
        }
        nameInput = nameList.toArray(new String[nameList.size()]);
        orgInput=orgList.toArray(new String[orgList.size()]);
        System.out.print(nameInput.length);
        rowItems = new ArrayList<RowItem>();

        for (int i = 0; i < nameInput.length; i++) 
        {
            RowItem items = new RowItem(nameInput[i],orgInput[i]);
            rowItems.add(items);
        }

        adapter = new CustomAdapter(getActivity(), rowItems);
        setListAdapter(adapter);
        getListView().setOnItemClickListener(this);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        Toast.makeText(getActivity(), nameInput[position], Toast.LENGTH_SHORT)
        .show();

    }


    @Override
    public boolean onClose() {
        // TODO Auto-generated method stub
        return false;
    }
    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {

        Organization.DISPLAY_NAME,
        Organization.COMPANY

    };

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // TODO Auto-generated method stub
        //String id5=id[iterator1];
        CursorLoader loader=null;
        String[] idArray=args.getStringArray("ID");
        String select = "((" + ContactsContract.CommonDataKinds.Organization.DISPLAY_NAME + " NOTNULL) AND ("+ ContactsContract.CommonDataKinds.Organization.COMPANY+"))";

        for(String id1:idArray)
        {
            //String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
            //String[] orgWhereParams = new String[]{id1,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}; 
            loader= new CursorLoader(getActivity(),ContactsContract.Data.CONTENT_URI,new String[]{Organization.DISPLAY_NAME,Organization.COMPANY},ContactsContract.Data.CONTACT_ID + " = " +id1+ " AND ContactsContract.Data.MIMETYPE = '"
                    + ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE
                    + "'",null,null);
            Cursor cursor=loader.loadInBackground();
            cursor.moveToFirst();
            String name=cursor.getString(cursor.getColumnIndex(Organization.DISPLAY_NAME));
            String orgname=cursor.getString(cursor.getColumnIndex(Organization.COMPANY));
            nameList.add(name);
            orgList.add(orgname);
            Log.d("Data",name);
            Log.d("Org",orgname);
        }
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // TODO Auto-generated method stub
        data.moveToFirst();
        String name=data.getString(data.getColumnIndex(Organization.DISPLAY_NAME));
        String orgname=data.getString(data.getColumnIndex(Organization.COMPANY));

        Log.d("Data",name);
        Log.d("Org",orgname);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        // TODO Auto-generated method stub

    }


}

3 个答案:

答案 0 :(得分:0)

试试这个

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
  transaction.beginTransaction()
                        .replace(R.id.container,new MyListFragment())
                        .commit();

答案 1 :(得分:0)

替换import android.app.ListFragment;同 import android.support.v4.app.ListFragment; 在每个项目文件中。 这有效......解决了问题

答案 2 :(得分:0)

我遇到了同样的问题,但首先您需要初始化您的课程,之后您需要在Alt+Intro变量中使用FragmentTransaction进行迁移。

确保导入android.support.v4.app.FragmentTransaction