动态更改片段标签主机中的片段?

时间:2013-08-08 07:40:56

标签: android android-fragments android-tabhost fragment-tab-host android-nested-fragment

我有一个主要的活动就是这里的片段活动我在B片段中设置两个片段A和B两个片段当用户点击按钮我想要将片段B更改为片段C时我有一个按钮。但是上面的标签是可见的......

如何在标签内替换片段?

非常感谢任何解决方案。

1 个答案:

答案 0 :(得分:92)

基本概念 - 我们可以通过创建容器来实现这一目标。将为每个选项卡分配一个特定容器。现在,当我们需要一个新片段时,我们将使用此容器替换相同的片段。

请逐步遵循下述代码,以便更好地理解。 第1步:为您的应用创建标签。说“Home.java”。它将包含使用片段创建标签的代码。

    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.FragmentTabHost;
    import android.widget.TextView;
    import app.drugs.talksooner.container.GoContainerFragment;
    import app.drugs.talksooner.container.LearnContainerFragment;
    import app.drugs.talksooner.container.MoreContainerFragment;
    import app.drugs.talksooner.container.TalkContainerFragment;
    import app.drugs.talksooner.container.WatchContainerFragment;
    import app.drugs.talksooner.utils.BaseContainerFragment;

    public class Home extends FragmentActivity {

        private static final String TAB_1_TAG = "tab_1";
        private static final String TAB_2_TAG = "tab_2";
        private static final String TAB_3_TAG = "tab_3";
        private static final String TAB_4_TAG = "tab_4";
        private static final String TAB_5_TAG = "tab_5";
        private FragmentTabHost mTabHost;

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

        private void initView() {
            mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
            mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

           // mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk", getResources().getDrawable(R.drawable.ic_launcher)), TalkContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_1_TAG).setIndicator("Talk"), TalkContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_2_TAG).setIndicator("Learn"), LearnContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_3_TAG).setIndicator("Go"), GoContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_4_TAG).setIndicator("Watch"), WatchContainerFragment.class, null);
            mTabHost.addTab(mTabHost.newTabSpec(TAB_5_TAG).setIndicator("More"), MoreContainerFragment.class, null);

            /* Increase tab height programatically 
             * tabs.getTabWidget().getChildAt(1).getLayoutParams().height = 150; 
             */

            for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
                final TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
                if (tv == null)
                continue;
                else
                tv.setTextSize(10);

            }

        }

        @Override
        public void onBackPressed() {
            boolean isPopFragment = false;
            String currentTabTag = mTabHost.getCurrentTabTag();
            if (currentTabTag.equals(TAB_1_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_1_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_2_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_2_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_3_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_3_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_4_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_4_TAG)).popFragment();
            } else if (currentTabTag.equals(TAB_5_TAG)) {
                isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(TAB_5_TAG)).popFragment();
            }
            if (!isPopFragment) {
                finish();
            }
        }


    }

您的home.xml文件

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

         <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />


        <android.support.v4.app.FragmentTabHost
            android:id="@android:id/tabhost"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="0dip"
                android:layout_height="0dip"
                android:layout_weight="0" />

        </android.support.v4.app.FragmentTabHost>

    </LinearLayout>

步骤2:定义基本容器片段,这将有助于回溯和替换片段“check out replaceFragement()”。我们的班级“BaseContainerFragment.java”

    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.util.Log;
    import app.drugs.talksooner.R;

    public class BaseContainerFragment extends Fragment {

        public void replaceFragment(Fragment fragment, boolean addToBackStack) {
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            if (addToBackStack) {
                transaction.addToBackStack(null);
            }
            transaction.replace(R.id.container_framelayout, fragment);
            transaction.commit();
            getChildFragmentManager().executePendingTransactions();
        }

        public boolean popFragment() {
            Log.e("test", "pop fragment: " + getChildFragmentManager().getBackStackEntryCount());
            boolean isPop = false;
            if (getChildFragmentManager().getBackStackEntryCount() > 0) {
                isPop = true;
                getChildFragmentManager().popBackStack();
            }
            return isPop;
        }

    }

Step3:现在我在这里考虑一个片段,只希望你可以用同样的方式处理休息。定义容器Fragment类。每个选项卡都有特定的容器。说第一个标签的TalkContainerFragment.java

    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import app.drugs.talksooner.R;
    import app.drugs.talksooner.Talk;
    import app.drugs.talksooner.utils.BaseContainerFragment;

    public class TalkContainerFragment extends BaseContainerFragment {

        private boolean mIsViewInited;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            Log.e("test", "tab 1 oncreateview");
            return inflater.inflate(R.layout.container_fragment, null);
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            Log.e("test", "tab 1 container on activity created");
            if (!mIsViewInited) {
                mIsViewInited = true;
                initView();
            }
        }

        private void initView() {
            Log.e("test", "tab 1 init view");
            replaceFragment(new Talk(), false);
        }

    }

这是xml文件。 “container_fragment.xml”此xml容器包含frameLayout。我们将使用此id替换不同的片段。

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container_framelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


    </FrameLayout>

你的主要课程。 “Talk.java”

    public class Talk extends Fragment {

        /** Define global variables over here */
        //private ProgressDialog pDialog;
        StaticApiList sal;
        TalkModelAll tma;
        JSONObject myJasonObject = null;
        private ListView lv;
        private ArrayList<TalkModelAll> m_ArrayList = null;
        //ArrayList<String> stringArrayList = new ArrayList<String>();
        TalkArrayAdapter taa;
        Set<String> uniqueValues = new HashSet<String>();
        TextView rowTextView = null;
        boolean vivek = false;

        int postid;
        String title;
        String thumsrc;
        String largeimg;
        String excert;
        String description;
        String cat;
        String myUrl;
        String jsonString;
        int mCurCheckPosition;
        String check_state = null;
        String ccc;
        LinearLayout myLinearLayout;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.talk, container, false);

            Button btn = (Button) rootView.findViewById(R.id.your_btn_id);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
//Here TalkDetail is name of class that needs to open
                    TalkDetail fragment = new TalkDetail();
                    // if U need to pass some data 
                    Bundle bundle = new Bundle();

                    bundle.putString("title", m_ArrayList.get(arg2).title);
                    bundle.putString("largeimg", m_ArrayList.get(arg2).largeimg);
                    bundle.putString("excert", m_ArrayList.get(arg2).excert);
                    bundle.putString("description", m_ArrayList.get(arg2).description);
                    bundle.putString("cat", m_ArrayList.get(arg2).cat);
                    //bundle.putInt("postid", m_ArrayList.get(arg2).postid);

                    fragment.setArguments(bundle);
                    ((BaseContainerFragment)getParentFragment()).replaceFragment(fragment, true);
                }
            });

            return rootView;
        }
    }

就是这样。你已准备好出发。整个魔术在于召唤R.id.而不是R.layout。 干杯!