在滑块菜单片段可插拔标签 [英] Swapable tabs in Slider Menu fragment

查看:124
本文介绍了在滑块菜单片段可插拔标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了导航抽屉通过参照本教程并现在我想要做的是显示一个片段内刷卡标签。也就是说当我点击导航抽屉里的项目,可以说是第一个,它应该显示刷卡选项卡的项目(我有6个片段在我的列表视图(同样: - A,B,C,D,E, F),我需要对我的一个片段3可插拔标签。)

如果该ITEM1的活动,当我点击它,那么它应该显示刷卡标签。

不过,我现在面临以下问题: -

  1. 我如何实现片段里面查看传呼机?

  2. 有可能的是,片段延伸的片段。

  3. 在片段延伸的FragmentActivity,然后在我的主要活动,code是否显示错误说类型不匹配,不能从片段的片段转换。

这是我的Deep.java文件

 包com.amar.demo;

进口info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
进口info.androidhive.slidingmenu.model.NavDrawerItem;

进口的java.util.ArrayList;

进口android.app.Activity;
进口android.app.Fragment;
进口android.app.FragmentManager;
进口android.content.res.Configuration;
进口android.content.res.TypedArray;
进口android.os.Bundle;
进口android.support.v4.app.ActionBarDrawerToggle;
进口android.support.v4.widget.DrawerLayout;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.AdapterView;
进口android.widget.ListView;

公共类深度延伸活动{
    私人DrawerLayout mDrawerLayout;
    私人的ListView mDrawerList;
    私人ActionBarDrawerToggle mDrawerToggle;

    //导航抽屉称号
    私人的CharSequence mDrawerTitle;

    //用于存储应用程序标题
    私人的CharSequence mTitle;

    //滑动菜单项
    私有String [] navMenuTitles;
    私人TypedArray navMenuIcons;

    私人的ArrayList< NavDrawerItem> navDrawerItems;
    私人NavDrawerListAdapter适配器;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.deep);

        mTitle = mDrawerTitle =的getTitle();

        //负荷滑动菜单项
        navMenuTitles = getResources()getStringArray(R.array.nav_drawer_items)。

        //导航抽屉,从资源的图标
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
        mDrawerList =(ListView控件)findViewById(R.id.list_slidermenu);

        navDrawerItems =新的ArrayList< NavDrawerItem>();

        //添加导航抽屉里的物品数组
        // 家
        navDrawerItems.add(新NavDrawerItem(navMenuTitles [0],navMenuIcons
                .getResourceId(0,-1)));
        //查找人​​员
        navDrawerItems.add(新NavDrawerItem(navMenuTitles [1],navMenuIcons
                .getResourceId(1,-1)));
        //照片
        navDrawerItems.add(新NavDrawerItem(navMenuTitles [2],navMenuIcons
                .getResourceId(2,-1)));
        //社区,这里将添加计数器
        navDrawerItems.add(新NavDrawerItem(navMenuTitles [3],navMenuIcons
                .getResourceId(3,-1),真,22));
        //网页
        navDrawerItems.add(新NavDrawerItem(navMenuTitles [4],navMenuIcons
                .getResourceId(4,-1)));
        //热点,我们将在这里添加计数器
        navDrawerItems.add(新NavDrawerItem(navMenuTitles [5],navMenuIcons
                .getResourceId(5,-1),真正的50+));

        //回收类型数组
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(新SlideMenuClickListener());

        //设置导航抽屉名单适配器
        适配器=新NavDrawerListAdapter(getApplicationContext()
                navDrawerItems);
        mDrawerList.setAdapter(适配器);

        //使操作栏中的应用程序图标,它表现为切换按钮
        getActionBar()setDisplayHomeAsUpEnabled(真)。
        getActionBar()setHomeButtonEnabled(真)。

        mDrawerToggle =新ActionBarDrawerToggle(这一点,mDrawerLayout,
                R.drawable.ic_drawer,//导航菜单切换图标
                R.string.app_name,//导航抽屉打开 - 说明
                                    //访问
                R.string.app_name //导航抽屉关闭 - 说明
                                    //访问
        ){
            公共无效onDrawerClosed(查看视图){
                。getActionBar()的setTitle(mTitle);
                //调用prepareOptionsMenu()来显示操作栏图标
                invalidateOptionsMenu();
            }

            公共无效onDrawerOpened(查看drawerView){
                。getActionBar()的setTitle(mDrawerTitle);
                //调用prepareOptionsMenu()隐藏操作栏图标
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        如果(savedInstanceState == NULL){
            //关于第一导航项目首次显示视图
            displayView(0);
        }
    }

    / **
     *滑动菜单项,点击监听器
     * * /
    私有类SlideMenuClickListener工具
            ListView.OnItemClickListener {
        @覆盖
        公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,
                长ID){
            对选定的导航抽屉的项目//显示视图
            displayView(位置);
        }
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        。getMenuInflater()膨胀(R.menu.testmenu,菜单);
        返回true;
    }

    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        //切换导航抽屉选择操作栏中的应用程序图标/标题
        如果(mDrawerToggle.onOptionsItemSelected(项目)){
            返回true;
        }
        //手柄操作栏操作点击
        开关(item.getItemId()){
        案例R.id.a_More:
            返回true;
        默认:
            返回super.onOptionsItemSelected(项目);
        }
    }

    / * *
     *当调用invalidateOptionsMenu()被触发
     * /
    @覆盖
    公共布尔prepareOptionsMenu(功能菜单)在{
        //如果导航抽屉被打开,隐藏行动项目
        布尔drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.a_More).setVisible(drawerOpen!);
        返回super.on prepareOptionsMenu(菜单);
    }

    / **
     * Diplaying片段视图选择导航抽屉列表项
     * * /
    私人无效displayView(INT位置){
        //更新替换片段的主要内容
        片段片段= NULL;
        开关(位置){
        情况下0:
            片段=新HomeFragment();
            打破;
        情况1:
            片段=新FindPeopleFragment();
            打破;
        案例2:
            片段=新PhotosFragment();
            打破;
        案例3:
            片段=新CommunityFragment();
            打破;
        壳体4:
            片段=新PagesFragment();
            打破;
        壳体5:
            片段=新WhatsHotFragment();
            打破;

        默认:
            打破;
        }

        如果(片段!= NULL){
            FragmentManager fragmentManager = getFragmentManager();
            // fragmentManager.beginTransaction()
            // .replace(R.id.frame_container,片段).commit();

            //更新所选项目和标题,然后关上抽屉
            mDrawerList.setItemChecked(位置,真正的);
            mDrawerList.setSelection(位置);
            的setTitle(navMenuTitles [位置]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } 其他 {
            //创建片段错误
            Log.e(MainActivity,创建片段错误);
        }
    }

    @覆盖
    公共无效的setTitle(CharSequence的标题){
        mTitle =称号;
        。getActionBar()的setTitle(mTitle);
    }

    / **
     *当使用ActionBarDrawerToggle,你必须在调用它
     * onPostCreate()和onConfigurationChanged()...
     * /

    @覆盖
    保护无效onPostCreate(包savedInstanceState){
        super.onPostCreate(savedInstanceState);
        //同步发生onRestoreInstanceState后切换状态。
        mDrawerToggle.syncState();
    }

    @覆盖
    公共无效onConfigurationChanged(配置NEWCONFIG){
        super.onConfigurationChanged(NEWCONFIG);
        //传递任何配置更改抽屉toggls
        mDrawerToggle.onConfigurationChanged(NEWCONFIG);
    }

}
 

在此$ C $词我在0的情况下所面临的问题。

这是我HomeFragment code: -         包com.amar.demo;

 进口android.app.ActionBar;
进口android.app.ActionBar.Tab;
进口android.app.FragmentTransaction;
进口android.os.Bundle;
进口android.support.v4.app.FragmentActivity;
进口android.support.v4.view.ViewPager;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;

进口com.amar.demo.adapter.TabsPagerAdapter;

公共类HomeFragment扩展FragmentActivity工具
        ActionBar.TabListener {

    私人ViewPager viewPager;
    私人TabsPagerAdapter mAdapter;
    私人ActionBar的动作条;
    //标签标题
    私有String []选项卡= {我的餐厅,娱乐,搜索和;书,
            新闻与更新};

    公共HomeFragment(){
    }

    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState){

        查看rootView = inflater.inflate(R.layout.fragment_home,集装箱,
                假);
        脊髓痨的// code
        viewPager =(ViewPager)rootView.findViewById(R.id.pager);
        动作条= getActionBar();
        mAdapter =新TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(假);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        //添加标签
        对于(字符串TAB_NAME:标签){
            actionBar.addTab(actionBar.newTab()的setText(TAB_NAME)
                    .setTabListener(本));
        }

        / **
         *上刷卡viewpager做出相应的选项卡中选择
         * * /

        viewPager.setOnPageChangeListener(新ViewPager.OnPageChangeListener(){

            @覆盖
            公共无效onPageSelected(INT位置){
                //在改变页面
                //使尊敬的选项卡中选择
                actionBar.setSelectedNavigationItem(位置);
            }

            @覆盖
            公共无效onPageScrolled(INT为arg0,浮动ARG1,ARG2 INT){
            }

            @覆盖
            公共无效onPageScrollStateChanged(INT为arg0){
            }
        });
        返回rootView;
    }

    @覆盖
    公共无效onTabSelected(TAB键,FragmentTransaction英尺){
        // TODO自动生成方法存根

    }

    @覆盖
    公共无效onTabUnselected(TAB键,FragmentTransaction英尺){
        // TODO自动生成方法存根

    }

    @覆盖
    公共无效onTabReselected(TAB键,FragmentTransaction英尺){
        // TODO自动生成方法存根

    }
}
 

这是我的deep.xml code: -         

 <! - 的FrameLayout显示片段 - >

    <的FrameLayout
        机器人:ID =@ + ID / frame_container
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent/>

    <! - 列表视图显示滑块菜单 - >

    <的ListView
        机器人:ID =@ + ID / list_slidermenu
        机器人:layout_width =240dp
        机器人:layout_height =match_parent
        机器人:layout_gravity =开始
        机器人:背景=@色/ list_background
        机器人:choiceMode =singleChoice
        机器人:分隔=@色/ list_divider
        机器人:dividerHeight =1DP
        机器人:listSelector =@可绘制/ list_selector/>

< /android.support.v4.widget.DrawerLayout>
 

这是我homefragment.xml code: -

 < android.support.v4.view.ViewPager的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:ID =@ + ID /寻呼机
机器人:layout_width =match_parent
机器人:layout_height =match_parent>
< /android.support.v4.view.ViewPager>
 

解决方案

您必须创建一个片段,包含ViewPager上有一个自定义布局。

请按照下列步骤,它将在整个过程中引导。

1。创建布局重新present的ViewPager,将其命名为fragment_main.xml

 < TabHost
    机器人:ID =@机器人:ID / tabhost
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>

    <的LinearLayout
        机器人:方向=垂直
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent>

        < TabWidget
            机器人:ID =@机器人:ID /标签
            机器人:方向=横向
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_weight =0/>

        <的FrameLayout
            机器人:ID =@机器人:ID / tabcontent
            机器人:layout_width =0dp
            机器人:layout_height =0dp
            机器人:layout_weight =0/>

        < android.support.v4.view.ViewPager
            机器人:ID =@ + ID /寻呼机
            机器人:layout_width =match_parent
            机器人:layout_height =0dp
            机器人:layout_weight =1/>

    < / LinearLayout中>
< / TabHost>
 

2。创建一个片段举行ViewPager上面的XML声明,将其命名为MyFragment.java

正如你所看到的,我们宣布在上面的XML声明的 TabHost ViewPager 等元素。此外,在该片段,我们膨胀之前创建的布局,以及 TabAdapter 来处理所有的标签。

 进口android.content.Context;
进口android.support.v4.app.FragmentActivity;
进口android.support.v4.app.FragmentPagerAdapter;
进口android.support.v4.view.ViewPager;
进口android.support.v4.app.Fragment;
进口android.os.Bundle;
进口android.view.LayoutInflater;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.TabHost;
进口android.widget.TabWidget;

进口的java.util.ArrayList;

公共静态类MyFragment扩展片段
{

    私人TabHost mTab​​Host;
    私人ViewPager mViewPager;
    私人TabsAdapter mTab​​sAdapter;

    公共MyFragment(){
    }

    @覆盖
    公共无效的onCreate(包实例)
    {
        super.onCreate(实例);

    }

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState){
        视图V = inflater.inflate(R.layout.fragment_main,集装箱,假);

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

        mViewPager =(ViewPager)v.findViewById(R.id.pager);
        mTabsAdapter =新TabsAdapter(getActivity(),mTabHost,mViewPager);

        //这里我们加载每个选项卡的内容。
        mTabsAdapter.addTab(mTabHost.newTabSpec(1)setIndicator(1),PageOneFragment.class,空);
        mTabsAdapter.addTab(mTabHost.newTabSpec(二)setIndicator(二),PageTwoFragment.class,空);

        返回伏;
    }

    公共静态类TabsAdapter扩展FragmentPagerAdapter实现TabHost.OnTabChangeListener,ViewPager.OnPageChangeListener
    {
        私人最终语境mContext;
        私人最终TabHost mTab​​Host;
        私人最终ViewPager mViewPager;
        私人最终的ArrayList< TabInfo> mTabs =新的ArrayList< TabInfo>();

        静态final类TabInfo
        {
            私人最终字符串标记;
            私人最终类别<> CLSS;
            私人最终捆绑的args;

            TabInfo(字符串_tag,类<> _class,捆绑_args)
            {
                标签= _tag;
                CLSS = _class;
                的args = _args;
            }
        }

        静态类DummyTabFactory实现TabHost.TabContentFactory
        {
            私人最终语境mContext;

            公共DummyTabFactory(上下文的背景下)
            {
                mContext =背景;
            }

            公共查看createTabContent(字符串标签)
            {
                视图V =新景(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                返回伏;
            }
        }

        公共TabsAdapter(FragmentActivity活动,TabHost tabHost,ViewPager寻呼机)
        {
            超级(activity.getSupportFragmentManager());
            mContext =活动;
            mTabHost = tabHost;
            mViewPager =寻呼机;
            mTabHost.setOnTabChangedListener(本);
            mViewPager.setAdapter(本);
            mViewPager.setOnPageChangeListener(本);
        }

        公共无效addTab(TabHost.TabSpec则tabspec,类<> CLSS,捆绑参数)
        {
            tabSpec.setContent(新DummyTabFactory(mContext));
            字符串变量= tabSpec.getTag();

            TabInfo信息=新TabInfo(标签,CLSS,参数);
            mTabs.add(信息);
            mTabHost.addTab(则tabspec);
            notifyDataSetChanged();
        }

        @覆盖
        公众诠释getCount将()
        {
            返回mTabs.size();
        }

        @覆盖
        公共片段的getItem(INT位置)
        {
            TabInfo信息= mTab​​s.get(位置);

            返回Fragment.instantiate(mContext,info.clss.getName(),info.args);

        }

        公共无效onTabChanged(字符串tabId)
        {
            INT位置= mTab​​Host.getCurrentTab();
            mViewPager.setCurrentItem(位置);
        }

        公共无效onPageScrolled(INT位置,浮positionOffset,诠释positionOffsetPixels)
        {
        }

        公共无效onPageSelected(INT位置)
        {
            //不幸的是,当TabHost改变当前选项卡,它亲切
            //也需要把重点放在它的时候不是在触摸模式的照顾。
            //挺举。
            //这个黑客试图prevent这从拉焦出于我们
            // ViewPager。
            TabWidget插件= mTab​​Host.getTabWidget();
            INT oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(位置);
            widget.setDescendantFocusability(oldFocusability);
        }

        公共无效onPageScrollStateChanged(INT状态)
        {
        }
    }
}
 

正如你所看到的,每个标签调用一个特定的片段。这些片段重新present每个选项卡的内容。因此,让我们创建它们,他们都非常简单,只包含一个的TextView

3。创建第一个选项卡的内容片段,将其命名为PageOneFragment.java

这个片段将举行第一个选项卡的内容。您可以在此片段里面放任何东西,它会生活脱离了其他碎片,并从其他选项卡。

下面我们夸大了 onCreateView 法里面的XML布局pageone_fragment.xml。我们将在下一步骤创建此xml布局

 进口android.app.Activity;
进口android.os.Bundle;
进口android.support.v4.app.Fragment;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;

公共类PageOneFragment扩展片段
{
    @覆盖
    公共无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState)
    {
        返回inflater.inflate(R.layout.pageone_fragment,集装箱,假);
    }

    @覆盖
    公共无效onActivityCreated(包savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
    }

    @覆盖
    公共无效onAttach(活动活动)
    {
        super.onAttach(活动);
    }

    @覆盖
    公共无效的OnStart()
    {
        super.onStart();
    }

    @覆盖
    公共无效onResume()
    {
        super.onResume();
    }
}
 

我们必须创建布局这个片段,因为我们前面提到的。

4。创建的PageOneFragment布局,将其命名为pageone_fragment.xml

这是只是一个的TextView 一个简单的布局,重新present的选项卡的内容。你可以建立你想要这个布局中任何东西,它会生活脱离了其他碎片和标签。

 < XML版本=1.0编码=UTF-8&GT?;
<的LinearLayout
    的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@ + ID / first_fragment
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直
    机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    机器人:后台=#ff4063ff>

    <的TextView
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:textAppearance =机器人:ATTR / textAppearanceMedium
        机器人:文本=第一页
        机器人:文字颜色=#FFFFFF
        机器人:TEXTSTYLE =黑体
        机器人:ID =@ + ID / firstFragmentTextView
        机器人:layout_gravity =center_horizo​​ntal |顶/>

< / LinearLayout中>
 

因为我们有两个选项卡,我们有两个片段,每个选项卡。因此,让我们创建第二个片段的第二个选项卡的内容。

5。创建片段的第二个选项卡的内容,将其命名为PageTwoFragment.java

正如你所看到的,我们膨胀的 onCreateView 方法,不同的布局,这就是所谓的 pagetwo_fragment.xml 。我们将在下一步创建它。

 进口android.app.Activity;
进口android.os.Bundle;
进口android.support.v4.app.Fragment;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;

公共类PageTwoFragment扩展片段
{
    @覆盖
    公共无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState)
    {
        返回inflater.inflate(R.layout.pagetwo_fragment,集装箱,假);
    }

    @覆盖
    公共无效onActivityCreated(包savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
    }

    @覆盖
    公共无效onAttach(活动活动)
    {
        super.onAttach(活动);
    }

    @覆盖
    公共无效的OnStart()
    {
        super.onStart();
    }

    @覆盖
    公共无效onResume()
    {
        super.onResume();
    }
}
 

正如我们之前所做的PageOneFragment,让我们创建了第二个片段的布局也正如我们前面提到的。

6。创建的PageTwoFragment布局,将其命名为pagetwo_fragment.xml

这是一个的TextView 一个简单的布局,只是为了重新present内容。你可以建立你要在这里任何东西,它会住得离其他碎片和制表符分隔。

 < XML版本=1.0编码=UTF-8&GT?;
<的LinearLayout
    的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@ + ID / first_fragment
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=垂直
    机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    机器人:后台=#ff4063ff>

    <的TextView
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:textAppearance =机器人:ATTR / textAppearanceMedium
        机器人:文本=第二页
        机器人:文字颜色=#FFFFFF
        机器人:TEXTSTYLE =黑体
        机器人:ID =@ + ID / firstFragmentTextView
        机器人:layout_gravity =center_horizo​​ntal |顶/>

< / LinearLayout中>
 


7。调用该片段从 NavigationDrawer

如果你想调用该片段从 NavigationDrawer 开关内部语句您的活动的 displayView(INT位置)方法,你应该这样做一个你的情况语句,例如。

  0的情况:
    片段=新MyFragment();
    打破;
 

以下是最终的结果

A ViewPager 在一个片段上运行,有两个选项卡均含有一个独特的内容独特的片段。

就是这样。

希望这有助于你。

I have implemented Navigation Drawer by Referring this tutorial and now what I want to do is to display swiping tabs inside a fragment. i.e. when i click on an item in navigation drawer, lets say the first one, it should display swiping tabs for that items.( I have 6 fragments in my list view.(likewise :- A,B,C,D,E,F). and I need 3 swapable tabs on my A Fragment.)

If the item1 is Events, when i click on it, then it should display swiping tabs.

But I am facing the following issues:-

  1. How can I implement view pager inside fragment?

  2. It is possible that a fragment extends a fragment.

  3. when A fragment is extending a FragmentActivity, then in my main activity, code is showing an error saying "type mismatch", can't convert from A Fragment to fragment.

This is my Deep.java file

    package com.amar.demo;

import info.androidhive.slidingmenu.adapter.NavDrawerListAdapter;
import info.androidhive.slidingmenu.model.NavDrawerItem;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class Deep extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

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

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
                .getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
                .getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
                .getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
                .getResourceId(3, -1), true, "22"));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
                .getResourceId(4, -1)));
        // What's hot, We will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
                .getResourceId(5, -1), true, "50+"));

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, // nav menu toggle icon
                R.string.app_name, // nav drawer open - description for
                                    // accessibility
                R.string.app_name // nav drawer close - description for
                                    // accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.a_More:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.a_More).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new FindPeopleFragment();
            break;
        case 2:
            fragment = new PhotosFragment();
            break;
        case 3:
            fragment = new CommunityFragment();
            break;
        case 4:
            fragment = new PagesFragment();
            break;
        case 5:
            fragment = new WhatsHotFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            // fragmentManager.beginTransaction()
            // .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

In this code i am facing problem in case 0.

This is my HomeFragment code :- package com.amar.demo;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amar.demo.adapter.TabsPagerAdapter;

public class HomeFragment extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "My Restaurant", "Offers", "Search & Book",
            "News & Updates" };

    public HomeFragment() {
    }

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

        View rootView = inflater.inflate(R.layout.fragment_home, container,
                false);
        // code of tabes
        viewPager = (ViewPager) rootView.findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

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

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        return rootView;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }
}

this is my deep.xml code :-

    <!-- Framelayout to display Fragments -->

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

    <!-- Listview to display slider menu -->

    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/list_background"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

</android.support.v4.widget.DrawerLayout>

This is my homefragment.xml code :-

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

解决方案

You must create a fragment with a custom layout that contains a ViewPager on it.

Follow these steps, it will guide in the entire process.

1. Create the layout to represent the ViewPager, name it fragment_main.xml

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

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

        <TabWidget
            android:id="@android:id/tabs"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>

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

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>
</TabHost>

2. Create a fragment to hold the ViewPager declared on the XML above, name it MyFragment.java

As you can see, we declare the TabHost the ViewPager and other elements declared in the XML above. Also in this fragment we inflate the layout created before, and a TabAdapter to handle all the tabs.

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;

import java.util.ArrayList;

public static class MyFragment extends Fragment
{

    private TabHost mTabHost;
    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;

    public MyFragment() {
    }

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

    }

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

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

        mViewPager = (ViewPager) v.findViewById(R.id.pager);
        mTabsAdapter = new TabsAdapter(getActivity(), mTabHost, mViewPager);

        // Here we load the content for each tab. 
        mTabsAdapter.addTab(mTabHost.newTabSpec("one").setIndicator("One"), PageOneFragment.class, null);
        mTabsAdapter.addTab(mTabHost.newTabSpec("two").setIndicator("Two"), PageTwoFragment.class, null);

        return v;
    }

    public static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener
    {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo
        {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args)
            {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory
        {
            private final Context mContext;

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

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

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager)
        {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args)
        {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount()
        {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position)
        {
            TabInfo info = mTabs.get(position);

            return Fragment.instantiate(mContext, info.clss.getName(), info.args);

        }

        public void onTabChanged(String tabId)
        {
            int position = mTabHost.getCurrentTab();
            mViewPager.setCurrentItem(position);
        }

        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
        {
        }

        public void onPageSelected(int position)
        {
            // Unfortunately when TabHost changes the current tab, it kindly
            // also takes care of putting focus on it when not in touch mode.
            // The jerk.
            // This hack tries to prevent this from pulling focus out of our
            // ViewPager.
            TabWidget widget = mTabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        public void onPageScrollStateChanged(int state)
        {
        }
    }
}

As you can see, each tab calls a specific fragment. These fragments represent the content for each tab. So let's create them, they are very simple, and contains only a TextView.

3. Create a fragment for the first tab content, name it PageOneFragment.java

This fragment will hold the content of the first tab. You can put anything inside this fragment, it will live separated from the other fragments and from the other tabs.

Here we inflate the xml layout pageone_fragment.xml inside the onCreateView method. We will create this xml layout in the next step.

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PageOneFragment extends Fragment
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

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

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

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

    @Override
    public void onStart()
    {
        super.onStart();
    }

    @Override
    public void onResume()
    {
        super.onResume();
    }
}

We must create the layout for this fragment as we mentioned before.

4. Create the layout for the PageOneFragment, name it pageone_fragment.xml

This is just a simple layout with a TextView to represent the content of the tab. You can build anything you want inside this layout, it will live separated from the other fragments and tabs.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/first_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ff4063ff">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="First Page"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:id="@+id/firstFragmentTextView"
        android:layout_gravity="center_horizontal|top" />

</LinearLayout>

As we have two tabs, we have two fragments, one for each tab. So let's create the second fragment for the second tab content.

5. Create the fragment for the second tab content, name it PageTwoFragment.java

As you can see, we inflate a different layout on the onCreateView method, it's called pagetwo_fragment.xml. We will create it on the next step.

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PageTwoFragment extends Fragment
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

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

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

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

    @Override
    public void onStart()
    {
        super.onStart();
    }

    @Override
    public void onResume()
    {
        super.onResume();
    }
}

And as we did before for the PageOneFragment, let's create the layout for the second fragment too, as we mentioned before.

6. Create the layout for the PageTwoFragment, name it pagetwo_fragment.xml

This is a simple layout with a single TextView, just to represent the content. You can build anything you want in here, it will live separated from the other fragments and tabs.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/first_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ff4063ff">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Second Page"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        android:id="@+id/firstFragmentTextView"
        android:layout_gravity="center_horizontal|top" />

</LinearLayout>


7. Call this fragment from your NavigationDrawer

If you want to call this fragment from your NavigationDrawer, inside the switch statement on your activity's displayView(int position) method, you should do this in one of your case statements, for example.

case 0:
    fragment = new MyFragment();
    break;

Here is the final result

A ViewPager running on a fragment, with two tabs each contains a unique fragment with a unique content.

That's it.

Hope this helps you.

这篇关于在滑块菜单片段可插拔标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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