如何显示滑动菜单栏在每一个活动? [英] How to show Sliding Menu Bar in every activity?

查看:232
本文介绍了如何显示滑动菜单栏在每一个活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林做了滑动菜单一个Android应用程序,但我希望它是avaliable所有活动。

下面是我的问题的一个例子:
我有7个主要选项(首页,翻译,旅游,设置等)命名的片段1至fragment7,
但我也有内巡回horizo​​ntalscrollview与其他活动,
我想这些其他活动,以显示滑动菜单藏汉..

我的继承人codeS


  

AndroidManifest.xml中


 <清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.gnirt69.slidingmenuexample>    <应用机器人:allowBackup =真正的机器人:标签=@字符串/ APP_NAME
        机器人:图标=@的mipmap / ic_launcher机器人:supportsRtl =真
        机器人:主题=@风格/ AppTheme>        <活动机器人:名字=机器人MainActivity:标签=导游与翻译>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.MAIN/>
                <类机器人:名字=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;        <活动机器人:touring.HotelsNAME =机器人:标签=导游与翻译>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.MAIN/>
                <类机器人:名字=android.intent.category.TAB/>
            &所述; /意图滤光器>
        < /活性GT;        <活动机器人:touring.HotspotsNAME =机器人:标签=导游与翻译>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.VIEW/>
                <类机器人:名字=android.intent.category.TAB/>
            &所述; /意图滤光器>
        < /活性GT;        <活动机器人:名字=机器人touring.Leisure:标签=导游与翻译>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.VIEW/>
                <类机器人:名字=android.intent.category.TAB/>
            &所述; /意图滤光器>
        < /活性GT;        <活动机器人:名字=机器人touring.Nightlife:标签=导游与翻译>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.VIEW/>
                <类机器人:名字=android.intent.category.TAB/>
            &所述; /意图滤光器>
        < /活性GT;        <活动机器人:touring.ResterauntsNAME =机器人:标签=导游与翻译>
            &所述;意图滤光器>
                <作用机器人:名字=android.intent.action.VIEW/>
                <类机器人:名字=android.intent.category.TAB/>
            &所述; /意图滤光器>
        < /活性GT;
    < /用途>
< /清单>


  

ItemSlideMenu.java


 包com.gnirt69.slidingmenuexample.model;
公共类ItemSlideMenu {    私人诠释imgId;
    私人字符串称号;    公共ItemSlideMenu(INT imgId,字符串名称){
        this.imgId = imgId;
        this.title =称号;
    }    公众诠释getImgId(){
        返回imgId;
    }    公共无效setImgId(INT imgId){
        this.imgId = imgId;
    }    公共字符串的getTitle(){
        返回称号;
    }    公共无效的setTitle(字符串名称){
        this.title =称号;
    }
}


  

MainActivity.java


 进口android.app.Fragment;
进口android.app.FragmentManager;
进口android.app.FragmentTransaction;
进口android.content.Intent;
进口android.os.Bundle;
进口android.support.v4.widget.DrawerLayout;
进口android.support.v7.app.ActionBarActivity;
进口android.support.v7.app.ActionBarDrawerToggle;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.ListView;
进口com.gnirt69.slidingmenuexample.adapter.SlidingMenuAdapter;
进口com.gnirt69.slidingmenuexample.fragment.Fragment1;
进口com.gnirt69.slidingmenuexample.fragment.Fragment2;
进口com.gnirt69.slidingmenuexample.fragment.Fragment3;
进口com.gnirt69.slidingmenuexample.fragment.Fragment4;
进口com.gnirt69.slidingmenuexample.fragment.Fragment5;
进口com.gnirt69.slidingmenuexample.fragment.Fragment6;
进口com.gnirt69.slidingmenuexample.fragment.Fragment7;
进口com.gnirt69.slidingmenuexample.touring.Hotels;
进口com.gnirt69.slidingmenuexample.model.ItemSlideMenu;
进口com.gnirt69.slidingmenuexample.touring.Hotspots;
进口com.gnirt69.slidingmenuexample.touring.Leisure;
进口com.gnirt69.slidingmenuexample.touring.Nightlife;
进口com.gnirt69.slidingmenuexample.touring.Resteraunts;进口的java.util.ArrayList;
进口的java.util.List;/ **
 *创建者的用户在2015年10月18日。
 * /
公共类MainActivity扩展ActionBarActivity {    私人列表< ItemSlideMenu> listSliding;
    私人SlidingMenuAdapter适配器;
    私人的ListView listViewSliding;
    私人DrawerLayout drawerLayout;
    私人ActionBarDrawerToggle actionBarDrawerToggle;
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main_activity);        //初始化组件
        listViewSliding =(ListView控件)findViewById(R.id.lv_sliding_menu);
        drawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
        listSliding =新的ArrayList<>();
        //滑动列表添加项目
        listSliding.add(新ItemSlideMenu(R.drawable.homeeee,家));
        listSliding.add(新ItemSlideMenu(R.drawable.tourrrr,导游));
        listSliding.add(新ItemSlideMenu(R.drawable.trrravel,翻译));
        listSliding.add(新ItemSlideMenu(R.drawable.settings_black,设置));
        listSliding.add(新ItemSlideMenu(R.mipmap.ic_launcher,帮助));
        listSliding.add(新ItemSlideMenu(R.mipmap.ic_launcher,关于));
        listSliding.add(新ItemSlideMenu(R.mipmap.ic_launcher,退出应用程序));
        适配器=新SlidingMenuAdapter(这一点,listSliding);
        listViewSliding.setAdapter(适配器);        //显示图标,打开/关闭滑动列表
        getSupportActionBar()setDisplayHomeAsUpEnabled(真)。        //设置标题
        的setTitle(listSliding.get(0).getTitle());
        //项目选择
        listViewSliding.setItemChecked(0,真);
        //关闭菜单
        drawerLayout.closeDrawer(listViewSliding);        //显示片段1时开始
        replaceFragment(0);
        // Hanlde上项目点击        listViewSliding.setOnItemClickListener(新AdapterView.OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
                //设置标题
                的setTitle(listSliding.get(位置).getTitle());
                //项目选择
                listViewSliding.setItemChecked(位置,真正的);
                //替换片段
                replaceFragment(位置);
                //关闭菜单
                drawerLayout.closeDrawer(listViewSliding);
            }
        });        actionBarDrawerToggle =新ActionBarDrawerToggle(这一点,drawerLayout,R.string.drawer_opened,R.string.drawer_closed){            @覆盖
            公共无效onDrawerOpened(查看drawerView){
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }            @覆盖
            公共无效onDrawerClosed(查看drawerView){
                super.onDrawerClosed(drawerView);
                invalidateOptionsMenu();
            }
        };        drawerLayout.setDrawerListener(actionBarDrawerToggle);
    }
    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        。getMenuInflater()膨胀(R.menu.main_menu,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){        如果(actionBarDrawerToggle.onOptionsItemSelected(项目)){
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }    @覆盖
    保护无效onPostCreate(捆绑savedInstanceState){
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }    //创建方法替代片段    私人无效replaceFragment(INT POS){
        片段片段= NULL;
        开关(POS){
            情况下0:
                片段=新片段1();
                打破;
            情况1:
                片段=新Fragment2();
                打破;
            案例2:
                片段=新Fragment3();
                打破;
            案例3:
                片段=新Fragment4();
                打破;
            情况4:
                片段=新Fragment5();
                打破;
            情况5:
                片段=新Fragment6();
                打破;
            情况6:
                片段=新Fragment7();
                打破;
            默认:
                片段=新片段1();
                打破;
        }        如果(NULL!=片段){
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction交易= fragmentManager.beginTransaction();
            transaction.replace(R.id.main_content,片段);
            transaction.addToBackStack(NULL);
            器transaction.commit();
        }
    }    公共无效sendHotels(查看视图){
        意图startNewActivity =新意图(这一点,Hotels.class);
        startActivity(startNewActivity);
    }
    公共无效sendHotspots(查看视图){
        意图startNewActivity =新意图(这一点,Hotspots.class);
        startActivity(startNewActivity);
    }
    公共无效sendLeisure(查看视图){
        意图startNewActivity =新意图(这一点,Leisure.class);
        startActivity(startNewActivity);
    }
    公共无效sendNightlife(查看视图){
        意图startNewActivity =新意图(这一点,Nightlife.class);
        startActivity(startNewActivity);    }
    公共无效sendResteraunt(查看视图){
        意图startNewActivity =新意图(这一点,Resteraunts.class);
        startActivity(startNewActivity);
    }}> main_activity.xml    < XML版本=1.0编码=UTF-8&GT?;
< android.support.v4.widget.DrawerLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:ID =@ + ID / drawer_layout
    机器人:方向=垂直>    < RelativeLayout的
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:ID =@ + ID / main_content>< / RelativeLayout的>    < ListView控件
        机器人:layout_width =200dp
        机器人:layout_height =match_parent
        机器人:ID =@ + ID / lv_sliding_menu
        机器人:背景=#FFFFFF
        机器人:choiceMode =singleChoice
        机器人:layout_gravity =开始>< /&的ListView GT;
< /android.support.v4.widget.DrawerLayout>> Fragment1.xml    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
        查看rootView = inflater.inflate(R.layout.fragment1,集装箱,FALSE);
        返回rootView;
    }> fragment1.xml< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直的android:layout_width =match_parent
    机器人:layout_height =match_parent>    <的TextView
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=家
        机器人:TEXTSIZE =30dp
        机器人:layout_gravity =中心/>
< / LinearLayout中>

和这里是我的问题,我想slidingmenu在这里也显示(内部片段1一活动)


  

Hotels.java


 包com.gnirt69.slidingmenuexample.touring;进口android.content.Intent;
进口android.os.Bundle;
进口android.support.v4.app.FragmentActivity;
进口android.view.View;进口com.gnirt69.slidingmenuexample.R;
/ **
 *创建者的用户在2015年12月14日。
 * /
公共类酒店扩展FragmentActivity {
    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.tourhotels);
    }    公共无效sendHotels(查看视图){
        意图startNewActivity =新意图(这一点,Hotels.class);
        startActivity(startNewActivity);
    }
    公共无效sendHotspots(查看视图){
        意图startNewActivity =新意图(这一点,Hotspots.class);
        startActivity(startNewActivity);
    }
    公共无效sendLeisure(查看视图){
        意图startNewActivity =新意图(这一点,Leisure.class);
        startActivity(startNewActivity);
    }
    公共无效sendNightlife(查看视图){
        意图startNewActivity =新意图(这一点,Nightlife.class);
        startActivity(startNewActivity);    }
    公共无效sendResteraunt(查看视图){
        意图startNewActivity =新意图(这一点,Resteraunts.class);
        startActivity(startNewActivity);
    }}


  

tourhotels.xml


 <的LinearLayout
        机器人:layout_height =FILL_PARENT
        机器人:layout_width =FILL_PARENT
        的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android>
        < Horizo​​ntalScrollView
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =WRAP_CONTENT>            <的LinearLayout
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:方向=横向>
                <按钮
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:文字=@字符串/ hotelss
                    机器人:ID =@ + ID / Hotelio
                    安卓的onClick =sendHotels/>
                <按钮
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:文字=@字符串/ resteraunts
                    安卓的onClick =sendResteraunt/>
                <按钮
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:文字=@字符串/ hotspotss
                    安卓的onClick =sendHotspots/>
                <按钮
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:文字=@字符串/休闲
                    安卓的onClick =sendLeisure/>
                <按钮
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT
                    机器人:文字=@字符串/夜生活
                    安卓的onClick =sendNightlife/>            < / LinearLayout中>
        < / Horizo​​ntalScrollView>
    < / LinearLayout中>


解决方案

解决了!对于谁想要一个TabHost添加到片段的任​​何人,这是我做到了。

不要忘了导入都在这里片段包含在导航抽屉


  

MainActivity.java


  DrawerLayout drawerLayout;
RelativeLayout的drawerPane;
ListView的lvNav;清单<&的NavItem GT; listNavItems;
清单<片断> listFragments;ActionBarDrawerToggle actionBarDrawerToggle;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    getSupportActionBar()setDisplayHomeAsUpEnabled(真)。    drawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
    drawerPane =(RelativeLayout的)findViewById(R.id.drawer_pane);
    lvNav =(ListView控件)findViewById(R.id.nav_list);    listNavItems =新的ArrayList<&的NavItem GT;();
    listNavItems.add(新的NavItem(家,是MyHome页
            R.drawable.ic_action_home));
    listNavItems.add(新的NavItem(翻译,英语宿务
            R.drawable.ic_action_home));
    listNavItems.add(新的NavItem(设置,改变的东西,
            R.drawable.ic_action_settings));
    listNavItems.add(新的NavItem(关于,作者的信息
            R.drawable.ic_action_about));    NavListAdapter navListAdapter =新NavListAdapter(
            getApplicationContext(),R.layout.item_nav_list,listNavItems);    lvNav.setAdapter(navListAdapter);    listFragments =新的ArrayList<片断>();
    listFragments.add(新是MyHome());
    listFragments.add(新MyTrans());
    listFragments.add(新MySettings());
    listFragments.add(新MyAbout());    //加载第一个片段为默认值:
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            。.replace(R.id.main_content,listFragments.get(0))提交();    的setTitle(listNavItems.get(0).getTitle());
    lvNav.setItemChecked(0,真);
    drawerLayout.closeDrawer(drawerPane);    //设置监听器导航项:
    lvNav.setOnItemClickListener(新OnItemClickListener(){
        @覆盖
        公共无效onItemClick(适配器视图<>母公司,观景,
                                INT位置,长的id){            //替换相应的选择片段:
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager
                    .beginTransaction()
                    .replace(R.id.main_content,listFragments.get(位置))
                    。承诺();            的setTitle(listNavItems.get(位置).getTitle());
            lvNav.setItemChecked(位置,真正的);
            drawerLayout.closeDrawer(drawerPane);        }
    });    //创建一个抽屉布局监听器
    actionBarDrawerToggle =新ActionBarDrawerToggle(这一点,drawerLayout,
            R.string.drawer_opened,R.string.drawer_closed){        @覆盖
        公共无效onDrawerOpened(查看drawerView){
            // TODO自动生成方法存根
            invalidateOptionsMenu();
            super.onDrawerOpened(drawerView);
        }        @覆盖
        公共无效onDrawerClosed(查看drawerView){
            // TODO自动生成方法存根
            invalidateOptionsMenu();
            super.onDrawerClosed(drawerView);
        }    };    drawerLayout.setDrawerListener(actionBarDrawerToggle);}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    //充气菜单;如果是present这增加了项目操作栏。    。getMenuInflater()膨胀(R.menu.menu_main,菜单);
    返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    //处理动作栏项目点击这里。操作栏会
    //自动处理点击的是MyHome /向上按钮,只要
    //你在AndroidManifest.xml中指定一个父活动。
    如果(actionBarDrawerToggle.onOptionsItemSelected(项目))
        返回true;    返回super.onOptionsItemSelected(项目);
}@覆盖
保护无效onPostCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
}

接下来是我出了问题,进口TabHost直接进入fragment.java类,藏汉作为onpagelistener(延长片段实现OnTabChangeListener)


  

MyTrans.java


  OnPageChangeListener {私人TabHost tabHost;
私人ViewPager viewPager;
私人MyFragmentPagerAdapter myViewPagerAdapter;
INT I = 0;
视图V;@覆盖
公共查看onCreateView(LayoutInflater气筒,
                         @Nullable的ViewGroup容器,@Nullable捆绑savedInstanceState){    V = inflater.inflate(R.layout.tabs_viewpager_layout,集装箱,FALSE);    我++;    //初始化tabhost
    this.initializeTabHost(savedInstanceState);    //初始化ViewPager
    this.initializeViewPager();
    返回伏;
}//为tabhost虚假内容
类FakeContent实现TabContentFactory {
    私人最终上下文mContext;    公共FakeContent(上下文的背景下){
        mContext =背景;
    }    @覆盖
    公共查看createTabContent(字符串标签){
        视图V =新景(mContext);
        v.setMinimumHeight(0);
        v.setMinimumWidth(0);
        返回伏;
    }
}私人无效initializeViewPager(){
    清单<片断>碎片=新的矢量<片断>();    fragments.add(新Tab1Fragment());
    fragments.add(新Tab2Fragment());
    fragments.add(新Tab3Fragment());    this.myViewPagerAdapter =新MyFragmentPagerAdapter(
            getChildFragmentManager(),片段);
    this.viewPager =(ViewPager)v.findViewById(R.id.viewPager);
    this.viewPager.setAdapter(this.myViewPagerAdapter);
    this.viewPager.setOnPageChangeListener(本);}私人无效initializeTabHost(捆绑参数){    tabHost =(TabHost)v.findViewById(android.R.id.tabhost);
    tabHost.setup();    的for(int i = 1; I< = 3;我++){        TabHost.TabSpec则tabspec;
        则tabspec = tabHost.newTabSpec(标签+ I);
        tabSpec.setIndicator(标签+ I);
        tabSpec.setContent(新FakeContent(getActivity()));
        tabHost.addTab(则tabspec);
    }
    tabHost.setOnTabChangedListener(本);
}@覆盖
公共无效onTabChanged(字符串tabId){
    INT POS = this.tabHost.getCurrentTab();
    this.viewPager.setCurrentItem(POS)    Horizo​​ntalScrollView hScrollView =(Horizo​​ntalScrollView)V
            .findViewById(R.id.hScrollView);
    查看TabView的= tabHost.getCurrentTabView();
    INT scrollPos = tabView.getLeft()
             - (hScrollView.getWidth() - tabView.getWidth())/ 2;
    hScrollView.smoothScrollTo(scrollPos,0);}@覆盖
公共无效onPageScrollStateChanged(INT为arg0){
}@覆盖
公共无效onPageScrolled(INT为arg0,ARG1浮球,诠释ARG2){
}@覆盖
公共无效使用onPageSelected(INT位置){
    this.tabHost.setCurrentTab(位置);
}

接下来,创建取决于你的howmany需要,使用充气类的标签

  @覆盖
公共查看onCreateView(LayoutInflater气筒,
        @Nullable的ViewGroup容器,@Nullable捆绑savedInstanceState){    视图V = inflater.inflate(R.layout.tab1fragment,集装箱,FALSE);    返回伏;
}

然后,你必须做出layout.xml文件来实现滚动视图,大小等。


  

tabs_viewpager_layout.xml


 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>    < TabHost
        机器人:ID =@机器人:ID / tabhost
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent>        <的LinearLayout
            机器人:layout_width =match_parent
            机器人:layout_height =match_parent
            机器人:方向=垂直>            < Horizo​​ntalScrollView
                机器人:ID =@ + ID / hScrollView
                机器人:layout_width =match_parent
                机器人:layout_height =WRAP_CONTENT
                机器人:fillViewport =真
                机器人:滚动条=无>                < TabWidget
                    机器人:ID =@机器人:ID /标签
                    机器人:layout_width =WRAP_CONTENT
                    机器人:layout_height =WRAP_CONTENT>
                < / TabWidget>
            < / Horizo​​ntalScrollView>            <的FrameLayout
                机器人:ID =@机器人:ID / tabcontent
                机器人:layout_width =match_parent
                机器人:layout_height =match_parent>                < android.support.v4.view.ViewPager
                    机器人:ID =@ + ID / viewPager
                    机器人:layout_width =match_parent
                    机器人:layout_height =match_parent/>
            < /&的FrameLayout GT;
        < / LinearLayout中>
    < / TabHost>< / LinearLayout中>

接下来,做出的.xml为每个标签页


  

tab1fragment.xml


 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>    <的TextView
        机器人:ID =@ + ID / textView1
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:TEXTSIZE =20SP
        机器人:文字=片段1/>

最后,不要忘了做一个.xml文件为每个导航抽屉(ofcourse ..)


  

fragment_tour.xml


 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直>    <的TextView
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文字=游
        机器人:文字颜色=#000
        机器人:TEXTSIZE =18sp
        机器人:文字样式=大胆/>< / LinearLayout中>

所以基本上,使片段中tabhostü希望上述<,<
现在听起来那么简单。

新年快乐大家。

Im making a android app with a sliding menu, but I want it to be avaliable for all activities.

Here is a example of my problem: I have 7 main options (Home, Translator, Tour, Settings etc) named fragment1 to fragment7, but I also have a horizontalscrollview inside Tour with other activities, I want these 'other activities' to show the Sliding Menu aswell..

Heres my codes

AndroidManifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gnirt69.slidingmenuexample">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher" android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Hotels" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Hotspots" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Leisure" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Nightlife" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Resteraunts" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>






    </application>


</manifest>

ItemSlideMenu.java

    package com.gnirt69.slidingmenuexample.model;


public class ItemSlideMenu {

    private int imgId;
    private String title;

    public ItemSlideMenu(int imgId, String title) {
        this.imgId = imgId;
        this.title = title;
    }

    public int getImgId() {
        return imgId;
    }

    public void setImgId(int imgId) {
        this.imgId = imgId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

MainActivity.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.gnirt69.slidingmenuexample.adapter.SlidingMenuAdapter;
import com.gnirt69.slidingmenuexample.fragment.Fragment1;
import com.gnirt69.slidingmenuexample.fragment.Fragment2;
import com.gnirt69.slidingmenuexample.fragment.Fragment3;
import com.gnirt69.slidingmenuexample.fragment.Fragment4;
import com.gnirt69.slidingmenuexample.fragment.Fragment5;
import com.gnirt69.slidingmenuexample.fragment.Fragment6;
import com.gnirt69.slidingmenuexample.fragment.Fragment7;
import com.gnirt69.slidingmenuexample.touring.Hotels;
import com.gnirt69.slidingmenuexample.model.ItemSlideMenu;
import com.gnirt69.slidingmenuexample.touring.Hotspots;
import com.gnirt69.slidingmenuexample.touring.Leisure;
import com.gnirt69.slidingmenuexample.touring.Nightlife;
import com.gnirt69.slidingmenuexample.touring.Resteraunts;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by User on 10/18/2015.
 */
public class MainActivity extends ActionBarActivity {

    private List<ItemSlideMenu> listSliding;
    private SlidingMenuAdapter adapter;
    private ListView listViewSliding;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;


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



        //Init component
        listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        listSliding = new ArrayList<>();
        //Add item for sliding list
        listSliding.add(new ItemSlideMenu(R.drawable.homeeee, "Home"));
        listSliding.add(new ItemSlideMenu(R.drawable.tourrrr, "Tour Guide"));
        listSliding.add(new ItemSlideMenu(R.drawable.trrravel, "Translator"));
        listSliding.add(new ItemSlideMenu(R.drawable.settings_black, "Settings"));
        listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "Help"));
        listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "About"));
        listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "Exit App"));
        adapter = new SlidingMenuAdapter(this, listSliding);
        listViewSliding.setAdapter(adapter);



        //Display icon to open/ close sliding list
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //Set title
        setTitle(listSliding.get(0).getTitle());
        //item selected
        listViewSliding.setItemChecked(0, true);
        //Close menu
        drawerLayout.closeDrawer(listViewSliding);

        //Display fragment 1 when start
        replaceFragment(0);
        //Hanlde on item click

        listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Set title
                setTitle(listSliding.get(position).getTitle());
                //item selected
                listViewSliding.setItemChecked(position, true);
                //Replace fragment
                replaceFragment(position);
                //Close menu
                drawerLayout.closeDrawer(listViewSliding);
            }
        });

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                invalidateOptionsMenu();
            }
        };

        drawerLayout.setDrawerListener(actionBarDrawerToggle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    //Create method replace fragment

    private void replaceFragment(int pos) {
        Fragment fragment = null;
        switch (pos) {
            case 0:
                fragment = new Fragment1();
                break;
            case 1:
                fragment = new Fragment2();
                break;
            case 2:
                fragment = new Fragment3();
                break;
            case 3:
                fragment = new Fragment4();
                break;
            case 4:
                fragment = new Fragment5();
                break;
            case 5:
                fragment = new Fragment6();
                break;
            case 6:
                fragment = new Fragment7();
                break;


            default:
                fragment = new Fragment1();
                break;
        }



        if(null!=fragment) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.main_content, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }


    }

    public void sendHotels(View view) {
        Intent startNewActivity = new Intent(this, Hotels.class);
        startActivity(startNewActivity);
    }
    public void sendHotspots(View view) {
        Intent startNewActivity = new Intent(this, Hotspots.class);
        startActivity(startNewActivity);
    }
    public void sendLeisure(View view) {
        Intent startNewActivity = new Intent(this, Leisure.class);
        startActivity(startNewActivity);
    }
    public void sendNightlife(View view) {
        Intent startNewActivity = new Intent(this, Nightlife.class);
        startActivity(startNewActivity);

    }
    public void sendResteraunt(View view) {
        Intent startNewActivity = new Intent(this, Resteraunts.class);
        startActivity(startNewActivity);
    }

}

> main_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_content"></RelativeLayout>

    <ListView
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:id="@+id/lv_sliding_menu"
        android:background="#FFFFFF"
        android:choiceMode="singleChoice"
        android:layout_gravity="start"></ListView>
</android.support.v4.widget.DrawerLayout>

> Fragment1.xml

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

> fragment1.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:textSize="30dp"
        android:layout_gravity="center"/>
</LinearLayout>

and here is my problem, I want the slidingmenu to show here also (a activity inside fragment1)

Hotels.java

       package com.gnirt69.slidingmenuexample.touring;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;

import com.gnirt69.slidingmenuexample.R;


/**
 * Created by User on 12/14/2015.
 */
public class Hotels extends FragmentActivity {




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

    public void sendHotels(View view) {
        Intent startNewActivity = new Intent(this, Hotels.class);
        startActivity(startNewActivity);
    }
    public void sendHotspots(View view) {
        Intent startNewActivity = new Intent(this, Hotspots.class);
        startActivity(startNewActivity);
    }
    public void sendLeisure(View view) {
        Intent startNewActivity = new Intent(this, Leisure.class);
        startActivity(startNewActivity);
    }
    public void sendNightlife(View view) {
        Intent startNewActivity = new Intent(this, Nightlife.class);
        startActivity(startNewActivity);

    }
    public void sendResteraunt(View view) {
        Intent startNewActivity = new Intent(this, Resteraunts.class);
        startActivity(startNewActivity);
    }

}

tourhotels.xml

     <LinearLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android" >
        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/hotelss"
                    android:id="@+id/Hotelio"
                    android:onClick="sendHotels"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/resteraunts"
                    android:onClick="sendResteraunt"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/hotspotss"
                    android:onClick="sendHotspots"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/leisure"
                    android:onClick="sendLeisure"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/nightlife"
                    android:onClick="sendNightlife"/>

            </LinearLayout>
        </HorizontalScrollView>
    </LinearLayout>

解决方案

Solved! for any others who wanted to add a TabHost into a Fragment this is how i did it..

Dont forget to import all your fragments here included in the Navigation Drawer

MainActivity.java

DrawerLayout drawerLayout;
RelativeLayout drawerPane;
ListView lvNav;

List<NavItem> listNavItems;
List<Fragment> listFragments;

ActionBarDrawerToggle actionBarDrawerToggle;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerPane = (RelativeLayout) findViewById(R.id.drawer_pane);
    lvNav = (ListView) findViewById(R.id.nav_list);

    listNavItems = new ArrayList<NavItem>();
    listNavItems.add(new NavItem("Home", "MyHome page",
            R.drawable.ic_action_home));
    listNavItems.add(new NavItem("Translator", "English Cebuano",
            R.drawable.ic_action_home));
    listNavItems.add(new NavItem("Settings", "Change something",
            R.drawable.ic_action_settings));
    listNavItems.add(new NavItem("About", "Author's information",
            R.drawable.ic_action_about));

    NavListAdapter navListAdapter = new NavListAdapter(
            getApplicationContext(), R.layout.item_nav_list, listNavItems);

    lvNav.setAdapter(navListAdapter);

    listFragments = new ArrayList<Fragment>();
    listFragments.add(new MyHome());
    listFragments.add(new MyTrans());
    listFragments.add(new MySettings());
    listFragments.add(new MyAbout());

    // load first fragment as default:
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.main_content, listFragments.get(0)).commit();

    setTitle(listNavItems.get(0).getTitle());
    lvNav.setItemChecked(0, true);
    drawerLayout.closeDrawer(drawerPane);

    // set listener for navigation items:
    lvNav.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // replace the fragment with the selection correspondingly:
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager
                    .beginTransaction()
                    .replace(R.id.main_content, listFragments.get(position))
                    .commit();

            setTitle(listNavItems.get(position).getTitle());
            lvNav.setItemChecked(position, true);
            drawerLayout.closeDrawer(drawerPane);

        }
    });

    // create listener for drawer layout
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
            R.string.drawer_opened, R.string.drawer_closed) {

        @Override
        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            invalidateOptionsMenu();
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            // TODO Auto-generated method stub
            invalidateOptionsMenu();
            super.onDrawerClosed(drawerView);
        }

    };

    drawerLayout.setDrawerListener(actionBarDrawerToggle);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the MyHome/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    if (actionBarDrawerToggle.onOptionsItemSelected(item))
        return true;

    return super.onOptionsItemSelected(item);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
}

Next is where i went wrong, import TabHost directly into the fragment.java class, aswell as the onpagelistener (extend Fragment implements OnTabChangeListener)

MyTrans.java

    OnPageChangeListener {

private TabHost tabHost;
private ViewPager viewPager;
private MyFragmentPagerAdapter myViewPagerAdapter;
int i = 0;
View v;

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

    v = inflater.inflate(R.layout.tabs_viewpager_layout, container, false);



    i++;

    // init tabhost
    this.initializeTabHost(savedInstanceState);

    // init ViewPager
    this.initializeViewPager();


    return v;
}

// fake content for tabhost
class FakeContent implements TabContentFactory {
    private final Context mContext;

    public FakeContent(Context context) {
        mContext = context;
    }

    @Override
    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumHeight(0);
        v.setMinimumWidth(0);
        return v;
    }
}

private void initializeViewPager() {
    List<Fragment> fragments = new Vector<Fragment>();

    fragments.add(new Tab1Fragment());
    fragments.add(new Tab2Fragment());
    fragments.add(new Tab3Fragment());

    this.myViewPagerAdapter = new MyFragmentPagerAdapter(
            getChildFragmentManager(), fragments);
    this.viewPager = (ViewPager) v.findViewById(R.id.viewPager);
    this.viewPager.setAdapter(this.myViewPagerAdapter);
    this.viewPager.setOnPageChangeListener(this);

}

private void initializeTabHost(Bundle args) {

    tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
    tabHost.setup();

    for (int i = 1; i <= 3; i++) {

        TabHost.TabSpec tabSpec;
        tabSpec = tabHost.newTabSpec("Tab " + i);
        tabSpec.setIndicator("Tab " + i);
        tabSpec.setContent(new FakeContent(getActivity()));
        tabHost.addTab(tabSpec);
    }
    tabHost.setOnTabChangedListener(this);
}

@Override
public void onTabChanged(String tabId) {
    int pos = this.tabHost.getCurrentTab();
    this.viewPager.setCurrentItem(pos);

    HorizontalScrollView hScrollView = (HorizontalScrollView) v
            .findViewById(R.id.hScrollView);
    View tabView = tabHost.getCurrentTabView();
    int scrollPos = tabView.getLeft()
            - (hScrollView.getWidth() - tabView.getWidth()) / 2;
    hScrollView.smoothScrollTo(scrollPos, 0);

}

@Override
public void onPageScrollStateChanged(int arg0) {
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageSelected(int position) {
    this.tabHost.setCurrentTab(position);
}

Next, create classes for your Tabs depending howmany you need, using inflater

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

    View v = inflater.inflate(R.layout.tab1fragment, container, false);

    return v;
}

Then you have to make a layout.xml file to implement scrollview, size etc.

tabs_viewpager_layout.xml

<?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" >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <HorizontalScrollView
                android:id="@+id/hScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true"
                android:scrollbars="none" >

                <TabWidget
                    android:id="@android:id/tabs"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >
                </TabWidget>
            </HorizontalScrollView>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewPager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>

Next, make a .xml for each of your tabs

tab1fragment.xml

<?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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Fragment 1" />

finally, dont forget to make a .xml file for each of your navigation drawers (ofcourse..)

fragment_tour.xml

<?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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tour"
        android:textColor="#000"
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

So basically, make the tabhost in the fragment u want it in <,< sounds so simple now..

happy new year everyone .

这篇关于如何显示滑动菜单栏在每一个活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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