ITKeyword,专注技术干货聚合推荐

注册 | 登录

解决android - Replace one fragment to another fragment in the TabHost

itPublisher 分享于

2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1062

2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址https://www.aliyun.com/minisite/goods

推荐:Android使用Fragment实现TabHost效果

本文转载自:http://www.fengfly.com/plus/view-215109-1.html 现在Fragment的应用真的是越来越广泛了,之前Android在3.0版本加入Fragment的时候,主要是为了解

I am creating a five tabs that contains one fragment each. I am using ListView in the first tab and in the ListView OnItemClickListener I want to replace from the first Tab Fragment to second tab Fragment. How can I do that by using Fragment and TabHost? I extends Fragment for main class and all fragment classes. I am not extends FragmentActivity. So how can I change the tab from one fragment to another fragment?

MainClass:

public class TabsFragment extends Fragment implements OnTabChangeListener {

    private View mRoot;
    public TabHost mTabHost;
    private int mCurrentTab;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mRoot = inflater.inflate(R.layout.tabs_fragment, null);
        mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
        setupTabs();
        return mRoot;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);

        mTabHost.setOnTabChangedListener(this);
        mTabHost.setCurrentTab(mCurrentTab);
        // manually start loading stuff in the first tab
        updateTab("1");
    }

    private void setupTabs() {
        mTabHost.setup(); // important!
        mTabHost.addTab(newTab("1", R.drawable.fragment1, R.id.fragment1));
        mTabHost.addTab(newTab("2", R.drawable.fragment2, R.id.fragment2));
        mTabHost.addTab(newTab("3", R.drawable.fragment3, R.id.fragment3));
        mTabHost.addTab(newTab("4", R.drawable.fragment4, R.id.fragment4));
        mTabHost.addTab(newTab("5", R.drawable.fragment5, R.id.fragment5));
    }

    private TabSpec newTab(String tag, int labelId, int tabContentId) {
        Log.d(TAG, "buildTab(): tag=" + tag);

        View indicator = LayoutInflater.from(getActivity()).inflate(
                R.layout.tab,
                (ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
        ((ImageView) indicator.findViewById(R.id.imageView1)).setImageResource(labelId);
        TabSpec tabSpec = mTabHost.newTabSpec(tag);
        tabSpec.setIndicator(indicator);
        tabSpec.setContent(tabContentId);
        return tabSpec;
    }

    @Override
    public void onTabChanged(String tabId) {
        updateTab(tabId);
        mCurrentTab = Integer.valueOf(tabId) - 1;
    }

    private void updateTab(String tabId) {
        FragmentManager fm = getFragmentManager();

        if (fm.findFragmentByTag(tabId) == null) {
            if (tabId.equals("1"))
                 fm.beginTransaction().replace(R.id.fragment1, new Fragment1(), tabId).commit();
            else if (tabId.equals("2"))
                fm.beginTransaction().replace(R.id.fragment2, new Fragment2(), tabId).commit();
            else if (tabId.equals("3"))
                fm.beginTransaction().replace(R.id.fragment3, new Fragment3(), tabId).commit();
            else if (tabId.equals("4"))
                fm.beginTransaction().replace(R.id.fragment4, new Fragment4(), tabId).commit();
            else if (tabId.equals("5"))
                fm.beginTransaction().replace(R.id.fragment5, new Fragment5(), tabId).commit();
        }
    }
}

Fragment1:

public class Fragment1 extends Fragment implements  OnItemClickListener {
    ListView listView;
    View theView;

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

        theView = inflater.inflate(R.layout.fragment1, container, false);
        listView = (ListView)theView.findViewById(R.id.list);
        listView.setOnItemClickListener(this);
        return theView;

    }

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

        // Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
        // How can I switch from 1st tab to 2nd tab here???
        // Below code is not worked for me.

        Fragment2 newFragment = new Fragment2();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.map, newFragment);
        transaction.commit();
    }
}

Fragment2:

public class Fragment2 extends SupportMapFragment {
    private LatLng mPosFija = new LatLng(37.878901,-4.779396);
    GoogleMap mapView;
    public Fragment2() {
        super();
    }

    public static Fragment2 newInstance(LatLng posicion) {
        Fragment2 frag = new Fragment2();
        frag.mPosFija = posicion;
        return frag;
    }
    @Override
    public void onResume() {
      super.onResume();
      initMap();
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.fragment2, container, false);
        view.setId(getId());
        SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview);
        mapView = fm.getMap();
        initMap();
        return view;
    }

    private void initMap() {
        UiSettings settings = mapView.getUiSettings();
        settings.setAllGesturesEnabled(true);
        settings.setMyLocationButtonEnabled(true);
        mapView.addMarker(new MarkerOptions().position(mPosFija).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
    }
}
android android-fragments android-tabhost fragment-tab-host
|
  this question
edited May 10 '16 at 15:50 Allan Pereira 2,088 4 11 26 asked Jun 15 '13 at 9:12 It's me 317 3 8 24 1   possible duplicate of Dynamically changing the fragments inside a fragment tab host? –  Qantas 94 Heavy Jul 14 '14 at 5:06

 | 

2 Answers
2

解决方法

Check out my post. This contains all you need with basic.

推荐:Android - TabHost 与 Fragment 制作页面切换效果

Android - TabHost 与 Fragment 制作页面切换效果 Android API 19 , API 23 三个标签页置于顶端 效果图: 在文件BoardTabHost.java中定义页面切换的效果;切换

Dynamically changing the fragments inside a fragment tab host?


|
  this answer
edited Nov 19 '13 at 6:06 laalto 96.4k 24 137 183 answered Nov 19 '13 at 5:46 AndroidHacker 2,899 13 32 3   This would likely be better as a comment as it is not a stand-alone answer. –  laalto Nov 19 '13 at 6:07      @laalto Will make sure for next. –  AndroidHacker Nov 19 '13 at 6:57

 | 

Did you find this question interesting? Try our newsletter

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Subscribed! Success! Please click the link in the confirmation email to activate your subscription. -1
NextFragment nextFrag = new NextFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack("next");
//container_framelayout: FrameLayout of Fragment to be replaced
transaction.replace(R.id.container_framelayout, nextFrag);
transaction.commit();

|
  this answer
edited Jun 19 '15 at 23:30 GuilhE 5,285 8 35 66 answered Jun 19 '15 at 21:42 omnia mahmoud 1 1      You should supply an explanation of the code. Code only answers are frowned on. –  Gary Storey Jun 19 '15 at 22:04      what is container_framelayout exactly –  behelit Mar 7 '16 at 5:45

 | 

推荐:android Fragments:管理fragment

要管理fragment们,需使用FragmentManager,要获取它,需在activity中调用方法getFragmentManager()。 你可以用FragmentManager来做以上事情:   1使用方法findF


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。