如何在每项活动中显示滑动菜单栏?

时间:2016-01-01 11:27:41

标签: java android xml android-layout android-fragments

我正在制作带有滑动菜单的Android应用程序,但我希望它适用于所有活动。

以下是我的问题示例: 我有7个主要选项(Home,Translator,Tour,Settings等),命名为fragment1到fragment7, 但是我也在巡回赛内有其他活动的横向视图, 我想要这些'其他活动'显示滑动菜单以及..

继承我的代码

  

的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>

这是我的问题,我希望slidemenu也显示在这里(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>

1 个答案:

答案 0 :(得分:0)

解决!对于任何想要将TabHost添加到片段中的人来说,这就是我做到的..

不要忘记导入导航抽屉中包含的所有片段

  

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();
}

接下来是我出错的地方,将TabHost直接导入fragment.java类,以及onpagelistener(extend Fragment实现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);
}

接下来,使用inflater

为您的标签创建类,具体取决于您的需要
@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

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

    return v;
}

然后你必须制作一个layout.xml文件来实现scrollview,size等。

  

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>

接下来,为每个标签创建一个.xml

  

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

最后,别忘了为每个导航抽屉制作一个.xml文件(当然..)

  

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>

所以基本上,在片段中制作tabhost你想要它在&lt;,&lt; 听起来很简单..

大家新年快乐。