【问题标题】:How do I add DrawerLayout in Every Activity?如何在每个 Activity 中添加 DrawerLayout?
【发布时间】:2015-12-31 13:34:13
【问题描述】:

在每个活动中添加侧边栏菜单 Sider 条码在这里 在 Home Activity 中它正在工作但使用其他 Activity 或扩展 Home Activity 但不工作

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public class Home extends ActionBarActivity  {

    protected DrawerLayout mDrawerLayout;
    protected ListView mDrawerList;
    protected ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    protected CharSequence mDrawerTitle;

    // used to store app title
    protected CharSequence mTitle;

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

    protected ArrayList<NavDrawerItem> navDrawerItems;
    protected NavDrawerListAdapter adapter;

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

        //if TheradPolicy When app crash automatically.
        //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

        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 Logout
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));


        // 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.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) {
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().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
     * */
    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.main, 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
     * */
    @SuppressLint("NewApi")
    protected 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 LogoutFragment();
            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");
        }
    }

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

}

此处有其他活动代码

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public class Sendsms extends Home {

    String id;
    InputStream is=null;
    String result=null;
    String line=null;
    public Typeface font;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.sendsms);

       StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

        Button select=(Button) findViewById(R.id.send_bulk_sms);
        // Click Listener
        select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                select();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    }




}

Smssens 活动 Xml 文件

<!-- copyrighted content owned by Android Arena (www.androidarena.co.in)-->
<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
        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:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"        
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:background="#e8e8e7"
        android:orientation="vertical" >

        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="48dp"
            android:background="#13b586"
            android:orientation="horizontal"
            android:layout_alignParentTop="true">


            <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send Sms"
            android:textColor="#ffffff"
            android:layout_marginLeft="25dp"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_gravity="center_horizontal|center_vertical"/>

            <LinearLayout  
            android:layout_width="fill_parent"
            android:layout_height="48dp"
            android:gravity="right"
            android:orientation="horizontal" >
            </LinearLayout>
   </LinearLayout>

        <LinearLayout android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginBottom="30dp"
            android:orientation="vertical"
            android:gravity="center_horizontal"
            android:background="@drawable/greybackground"
            >

            <ImageView android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@drawable/logo"
                android:layout_marginTop="15dp"
                android:layout_gravity="center_horizontal"/>
             <TextView
            android:id="@+id/tvInvisibleError"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_alignRight="@+id/simple_spinner_item"
            android:layout_alignBottom="@+id/simple_spinner_item"
            android:layout_marginTop="0dp"
            android:paddingTop="0dp"
            android:paddingRight="50dp"
            android:focusable="true"
            android:focusableInTouchMode="true"
            />
             <LinearLayout 
       android:layout_marginTop="10dp"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
     android:gravity="center_horizontal">

  </LinearLayout>
             <Button android:layout_width="190dp"
                 android:layout_height="38dp"
                 android:layout_gravity="center_horizontal"
                 android:layout_marginTop="16dp"
                 android:id="@+id/send_bulk_sms"
                 android:text="Send Bulk Sms"
                 android:textColor="#fff"
                 android:textSize="13dp"
                 android:background="#13b586"/>

        </LinearLayout>

</LinearLayout>

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

【问题讨论】:

  • 你必须使用片段
  • 什么是Home,你在其他类中扩展了
  • 是 Home 是侧边栏菜单正常工作的其他类
  • 只创建一个 Activity 并用片段替换中心内容。

标签: android android-fragments android-menu


【解决方案1】:

实现一个 BaseActivity,你所有的带有抽屉菜单的活动都应该扩展,并将抽屉的逻辑放在那个父活动中。更多详情here

【讨论】:

  • 在我的例子中 Home 是 BaseActivity 类
  • 这应该包括你的家庭活动,BaseActivty 应该是你所有活动的抽象父项
【解决方案2】:

您需要使用fragments 并从您的Activity 调用它。

使用片段,您可以多次使用相同的侧边栏,即在不同的活动中。

即使是导航抽屉,也可以很容易地使用带有活动的片段。

例如,

主页活动滑动菜单工作,但在发送消息活动中如何显示?

您可以在片段中制作一个滑动菜单并从两个活动中调用它

通过this link 了解更多详情。 这是another link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多