Android ActionBarCompat - 带有多个片段的导航抽屉

时间:2014-01-24 04:41:07

标签: android android-fragments android-actionbar

我是ActionBarCompat库的新手。我想开发一个包含多个片段的应用程序。这就是我想做的事情

1.当用户从导航抽屉中选择片段时,如何打开片段。

2.如何设置显示启动布局的启动片段(例如 - 在Google plus app中,首先显示新闻源。当我们从侧面菜单中选择个人资料项目时,它会隐藏侧面菜单/导航抽屉并显示配置文件布局)

目前我有侧边菜单和一个片段。 以下是我过去遵循的教程 - wptrafficanalyzer

4 个答案:

答案 0 :(得分:1)

我假设通过侧边菜单你的意思是导航抽屉。您可以在以下链接中找到答案。

Navigation Drawer with backword compatibility android

请阅读

http://developer.android.com/design/patterns/navigation-drawer.html

片段由活动托管。因此,您需要活动布局中的容器。

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout                  // container to which you add or replace fragments
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <ListView                     
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"/>

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

最初,您不要点击任何项目。所以最初将fragment1添加到容器中。

 FragmentTransaction fragTran = getSupportFragmentManager()
                                       .beginTransaction();
 Fragment fragment1= new Fragment1();
 fragTran.add(R.id.content_frame, fragment1);
 fragTran.commit(); 

根据位置点击listitem

 FragmentTransaction fragTran = getSupportFragmentManager()
                                       .beginTransaction();
 Fragment fragment3= new Fragment3();
 fragTran.replace(R.id.content_frame, fragment3);
 fragTran.commit(); 

答案 1 :(得分:1)

如果您打算使用滑出式菜单,我建议您使用此slidemenu library我在我的应用程序中使用它,它允许您在幻灯片菜单中放置任何您想要的内容,菜单只是一个框架布局,你可以把任何你想要的东西(Listview,GridView,甚至只是一张图片)

答案 2 :(得分:1)

  

您好检查此代码

公共类MainActivity扩展了ActionBarActivity实现         OnItemClickListener {

DrawerLayout options_drawer;
FrameLayout main_frame;
ListView slider_list;
ActionBar action;
ActionBarDrawerToggle toggler;

BluetoothAdapter blue_adapter;

String options[] = { "Chat", "Device List", "Settings", "Emojis",
        "Terms&Conditions" };

Fragment f;

private static final int REQUEST_ENABLE_BT = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activity_main);
    // setSupportProgressBarIndeterminateVisibility(true);
    action = getSupportActionBar();
    action.setHomeButtonEnabled(true);
    action.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    options_drawer = (DrawerLayout) findViewById(R.id.drawer);
    main_frame = (FrameLayout) findViewById(R.id.main_frame);
    slider_list = (ListView) findViewById(R.id.slider_list);

    blue_adapter = BluetoothAdapter.getDefaultAdapter();
    if (blue_adapter == null) {
        Toast.makeText(getApplicationContext(),
                "NO BLUETOOTH DEVICE FOUND", Toast.LENGTH_LONG).show();
        finish();
    }

    ArrayAdapter<String> al = new ArrayAdapter<String>(
            getApplicationContext(), R.layout.option_text, options);
    slider_list.setAdapter(al);
    slider_list.setOnItemClickListener(this);

    /*
     * toggler=new ActionBarDrawerToggle(MainActivity.this,
     * options_drawer,R.
     * drawable.ic_launcher,R.string.app_name,R.string.app_name){
     * 
     * @Override public void onDrawerOpened(View drawerView) { // TODO
     * Auto-generated method stub super.onDrawerOpened(drawerView);
     * options_drawer.openDrawer(slider_list); }
     * 
     * };
     */
    // options_drawer.setDrawerListener(toggler);

    if (savedInstanceState == null) {

        f = new chat_fragment();
        fragmentTransition(f);

    }

}

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

    // If BT is not on, request that it be enabled.
    // setupChat() will then be called during onActivityResult
    if (!blue_adapter.isEnabled()) {
        Intent enableIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    if (item.getItemId() == android.R.id.home) {

        // If the drawer is open, close it; vice versa
        if (options_drawer.isDrawerOpen(slider_list)) {
            options_drawer.closeDrawer(slider_list);
        } else {
            options_drawer.openDrawer(slider_list);
        }
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
        long arg3) {
    // TODO Auto-generated method stub

    options_drawer.closeDrawer(slider_list);

    switch (position) {

    case 0:
        f = new chat_fragment();
        fragmentTransition(f);
        break;

    case 1:

        f = new device_list_fragment();
        fragmentTransition(f);
        break;
    }


}

private void fragmentTransition(Fragment f2) {
    // TODO Auto-generated method stub

    FragmentTransaction fx = getSupportFragmentManager().beginTransaction();
    fx.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    fx.replace(R.id.main_frame, f2).commit();

}

}

XML文件是

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

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

<ListView
    android:id="@+id/slider_list"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#ffffff" >
</ListView>

答案 3 :(得分:1)

试试这个链接 http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/ android actionbarcompat是以下android版本支持的库。在这里你应该对代码进行一些修改。我给出了一些支持库的示例代码

代码:

public class SliderScreen extends ActionBarActivity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    int checkboxValue=0;
    // nav drawer title
    private CharSequence mDrawerTitle;
    private int selectedPosition=0;
    private int currentpos=0;
    // used to store app title
    private CharSequence mTitle;
    ProgressDialog progress_dialog;
    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;
    public static String letter = "";
    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;
    ActionBarActivity activity;
    MDatabase mdatabaseHelper;
    String contact_id = "";
    Cursor contactsCursor = null, databaseCursor = null,
            messageDatabaseCursor = null,imageDatabaseCursor=null;
    String contactCursorValue = "0";
    int contactCursorRead = 0, messageCursorRead = 0,imageCursorRead=0;
    int messageProgressValue = 0, contactProgressValue = 0,imageProgressValue=0;
     AlertDialog d;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.slide_screen);

        mTitle = mDrawerTitle = getTitle();
        // activity=(ActionBarActivity) Context.getApplicationContext();

        // 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);

        progress_dialog = new ProgressDialog(SliderScreen.this);
        progress_dialog.setMessage("please wait  ");

        Builder build=new Builder(SliderScreen.this);
        build.setTitle("");
        build.setMessage("Do you want to signout ? ");
        build.setPositiveButton("Yes",new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                finish();

            }
        });
        build.setNegativeButton("No",new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                d.dismiss();

            }
        });
        d=build.create();

        // Database retrieval

        mdatabaseHelper = new MDatabase(SliderScreen.this, null, null, 1);
        mdatabaseHelper.getWritableDatabase();
        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), true, 0));

        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
                .getResourceId(2, -1), true, 0));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
                .getResourceId(3, -1), true,0));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
                .getResourceId(4, -1), true, getMusicFilesCount()));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
                .getResourceId(5, -1)));
        // What's hot, We will add a counter here

        // 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
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.listbulletes, // nav menu toggle icon
                0, // nav drawer open - description for accessibility
                0 // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(mTitle);
                if(currentpos!=selectedPosition)
                {
                    currentpos=selectedPosition;
                    displayView(selectedPosition);
                }

            }


            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setTitle(mDrawerTitle);

                // calling onPrepareOptionsMenu() to hide action bar icons

                // ActivityCompat.invalidateOptionsMenu(getParent());
                // invalidateOptionsMenu();
            }

        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

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



    }


    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            if(currentpos!=position)
            {
                Fragment fragment=new DefaultFragment();
                if (fragment != null) {
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment).commit();

                    // update selected item and title, then close the drawer

                    setTitle(" ");
                } else {
                    // error in creating fragment
                    Log.e("MainActivity", "Error in creating fragment");
                }
            }

            selectedPosition=position;
            mDrawerLayout.closeDrawer(mDrawerList);
            /*
            // display view for selected nav drawer item
            if(selectedPosition==position)
            {
                 mDrawerLayout.closeDrawer(mDrawerList);
            }
            else
            {
                displayView(position);
                selectedPosition=position;
            }

        */}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, 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.action_settings:
            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.action_settings).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 ContactsFragment();

            break;
        case 2:

                fragment = new MessagesFragment();

            break;
        case 3:

                fragment = new ImageFragment();

            break;
        case 4:
            fragment = new MusicFragment();
            break;
        case 5:
            fragment = new SettingsFragment();
            break;

        default:
            break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            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");
        }
    }

    private void showProgressDialog() {

        progress_dialog.show();

    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().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);
    }



}