android - 如何在每个 Activity 中添加 DrawerLayout?

标签 android android-fragments android-menu

在每个 Activity 中添加侧边栏菜单 侧边栏代码在这里 在家庭 Activity 中它可以工作但使用其他 Activity 或扩展家庭 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);
    }

}

此处有其他 Activity 代码

@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 Activity 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>

最佳答案

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

关于android - 如何在每个 Activity 中添加 DrawerLayout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34547233/

相关文章:

java - 与 com.google.android.gms.maps.SupportMapFragment 的另一个 fragment 重复 ID、标记 null 或父 ID 0x0

android - 如何更改底部导航按钮单击的 Activity ?

android - 覆盖android上的物理菜单按钮

java - 如何将自定义布局设置为菜单项?

Android:如何切换 RecyclerView 列表的布局?

android - 如何在Android应用程序中支持GESTURE、左/右滑动、多种过渡效果

java - GCM 通知接收器/ token 注册

android - 如何向操作栏/工具栏添加后退按钮

java - 通过接口(interface)发送数组列表会导致类转换异常吗?

android - 无法解析符号 'menu' ?