【问题标题】:Navigation Drawer with backword compatibility android具有向后兼容性android的导航抽屉
【发布时间】:2013-11-20 05:41:13
【问题描述】:

我有一个应用程序,它有四个不同的活动。现在我想在应用程序中添加一个导航抽屉来导航这些活动。任何人都可以为不同活动的导航抽屉提供示例或教程,并具有回词兼容性。我已经看过片段示例,但我需要活动示例。

【问题讨论】:

    标签: android android-fragments android-actionbar navigation-drawer


    【解决方案1】:

    您需要使用支持库中的 appcompact。

    您的活动需要扩展ActionBarActivity。

    在你的活动中

     public class MainActivity extends ActionBarActivity {
    

    导入

     import android.support.v7.app.ActionBarActivity;
    

    用getSupportActionbar()代替getActionBar()

    使用Them.AppCompact

    或者使用 ActionBarSherlock 库。

    https://stackoverflow.com/questions/20071004/add-icon-in-drawerlist-by-actionbarsherlock/20077469#20077469

    例子:

    MainActivity.java

    public class MainActivity extends ActionBarActivity {
    
        // Fields -----------------------------------------------------------------
        private DrawerLayout drawerLayout;
        private ListView drawerList;
        private ActionBarDrawerToggle drawerToggle;
        private MenuListAdapter menuAdapter;
        private int[] icons;
        private Fragment fragment1;
        private Fragment fragment2;
        private Fragment fragment3;
        private CharSequence drawerTitle;
        private CharSequence title;
        private final String[] titles = new String[]{
                "Title Fragment #1",
                "Title Fragment #2",
                "Title Fragment #3"
        };
        private final String[] subtitles = new String[]{
                "Subtitle Fragment #1",
                "Subtitle Fragment #2",
                "Subtitle Fragment #3"
        };
    
        // Lifecycle Callbacks ----------------------------------------------------
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            // Base implemenation
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Instantiate the fragments
            fragment1 = new Fragment1();
            fragment2 = new Fragment2();
            fragment3 = new Fragment3();
    
            // Get the title from this activity
            title = drawerTitle = getTitle();
    
            // Get the icons from the drawables folder
            icons = new int[]{
                    R.drawable.action_about,
                    R.drawable.action_settings,
                    R.drawable.collections_cloud
            };
    
            // Get the drawer layout from the XML file and the ListView inside it
            drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
            drawerList = (ListView)findViewById(R.id.listview_drawer);
    
            // Set a custom shadow over that overlays the main content
            // when the drawer opens
            drawerLayout.setDrawerShadow(
                    R.drawable.drawer_shadow, GravityCompat.START);
    
            // Pass the string arrays to the MenuListAdapter, set the drawer
            // list adapter to it and set up its click listener
            menuAdapter = new MenuListAdapter(
                    MainActivity.this, titles, subtitles, icons);
            drawerList.setAdapter(menuAdapter);
            drawerList.setOnItemClickListener(new DrawerItemClickListener());
    
            // Enable the action bar to have up navigation
            getSupportActionBar().setHomeButtonEnabled(true);
            //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            // Allow the the action bar to toggle the drawer
            drawerToggle = new ActionBarDrawerToggle(
                    this,
                    drawerLayout,
                    R.drawable.ic_drawer,
                    R.string.drawer_open,
                    R.string.drawer_close){
    
                public void onDrawerClosed(View view){
                    super.onDrawerClosed(view);
                }
                public void onDrawerOpened(View view){
                    getSupportActionBar().setTitle(drawerTitle);
                    super.onDrawerOpened(view);
                }
            };
            drawerLayout.setDrawerListener(drawerToggle);
    
            // If this is the first time opening this activity,
            // start with loading fragment #1
            if (savedInstanceState == null){
                selectItem(0);
            }       
    
        }
    
        // Methods ----------------------------------------------------------------
        @Override
        public boolean onOptionsItemSelected(MenuItem item){
    
            // If the user has pressed the action bar icon
            if (item.getItemId() == android.R.id.home){
    
                // If the drawer is open, close it; vice versa
                if (drawerLayout.isDrawerOpen(drawerList)){
                    drawerLayout.closeDrawer(drawerList);
                } else {
                    drawerLayout.openDrawer(drawerList);
                }
            }
    
            // Finish by letting the super class do the rest
            return super.onOptionsItemSelected(item);
    
        }
        @Override
        protected void onPostCreate(Bundle savedInstanceState){
    
            // Call the super implementation and synchronize the drawer
            super.onPostCreate(savedInstanceState);
            drawerToggle.syncState();
    
        }
        @Override
        public void onConfigurationChanged(Configuration newConfig){
    
            // Call the super implemenation on this activity
            // and the drawer toggle object
            super.onConfigurationChanged(newConfig);
            drawerToggle.onConfigurationChanged(newConfig);
    
        }
        private void selectItem(int position){
    
            // Create a new fragment transaction and start it
            FragmentTransaction fragTran = getSupportFragmentManager()
                                           .beginTransaction();
    
            // Locate the position selected replace the content view
            // with the fragment of the number selected
            switch (position){
                case 0:{
                    fragTran.replace(R.id.content_frame, fragment1);
                    break;
                }
                case 1:{
                    fragTran.replace(R.id.content_frame, fragment2);
                    break;
                }
                case 2:{
                    fragTran.replace(R.id.content_frame, fragment3);
                    break;
                }
            }
    
            // Commit the transaction and close the drawer
            fragTran.commit();
            drawerList.setItemChecked(position, true);
            drawerLayout.closeDrawer(drawerList);
    
        }
        public void setTitle(CharSequence title){
    
            // Save the passed in title and set the action bar title
            this.title = title;
            getSupportActionBar().setTitle(title);
    
        }
    
        // Classes ----------------------------------------------------------------
        private class DrawerItemClickListener 
        implements ListView.OnItemClickListener{
    
            @Override
            public void onItemClick(
                    AdapterView<?> parent, 
                    View view, 
                    int position,
                    long id) {
    
                // When clicked, select open the appropriate fragment
                selectItem(position);
    
            }
    
        }
    
    }
    

    activity_main.xml

    <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/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
        <ListView 
            android:id="@+id/listview_drawer"
            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>
    
    public class MenuListAdapter extends BaseAdapter {
    
        // Fields -----------------------------------------------------------------
        private Context mcontext;
        private String[] titles;
        private String[] subtitles;
        private int[] icons;
        private LayoutInflater inflater;
    
        // Constructor ------------------------------------------------------------
        public MenuListAdapter(
                Context context, 
                String[] titles, 
                String[] subtitles,
                int[] icons){
            mcontext = context;
            this.titles = titles;
            this.subtitles = subtitles;
            this.icons = icons;
            inflater = (LayoutInflater)mcontext.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
        }
    
        // Accessors --------------------------------------------------------------
        @Override
        public int getCount(){
            return titles.length;
        }
        @Override
        public Object getItem(int position){
            return titles[position];
        }
        @Override
        public long getItemId(int position){
            return position;
        }
    
        // Methods ----------------------------------------------------------------
        public View getView(int position, View convertView, ViewGroup parent){
    
            ViewHolder viewHolder;
    
            // Only inflate the view if convertView is null
            if (convertView == null){
                viewHolder = new ViewHolder();
                if(inflater!=null)
                {
                convertView = inflater.inflate(
                        R.layout.drawer_list_item, parent, false);
                viewHolder.txtTitle = (TextView)convertView.findViewById(
                        R.id.title);
                viewHolder.txtSubtitle = (TextView)convertView.findViewById(
                        R.id.subtitle);
                viewHolder.imgIcon = (ImageView)convertView.findViewById(
                        R.id.icon);
    
                // This is the first time this view has been inflated,
                // so store the view holder in its tag fields
                convertView.setTag(viewHolder);
                }
                else
                {
                    Log.i("........",""+null);
                }
            } else {
                viewHolder = (ViewHolder)convertView.getTag();
            }
    
            // Set the views fields as needed
            viewHolder.txtTitle.setText(titles[position]);
            viewHolder.txtSubtitle.setText(subtitles[position]);
            viewHolder.imgIcon.setImageResource(icons[position]);
    
            return convertView;
        }
    
        // Classes ----------------------------------------------------------------
        static class ViewHolder {
            TextView txtTitle;
            TextView txtSubtitle;
            ImageView imgIcon;
        }
    
    }
    

    drawr_list_item.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:background="@android:color/darker_gray"
        android:orientation="horizontal"
        style="?attr/dropdownListPreferredItemHeight" >
    
        <ImageView
            android:id="@+id/icon"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"/>
    
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical|left"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:singleLine="true"
                style="?attr/spinnerDropDownItemStyle"/>
            <TextView 
                android:id="@+id/subtitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:singleLine="true"
                style="?attr/spinnerDropDownItemStyle"/>
    
        </LinearLayout>    
    
    </LinearLayout>
    

    fragment1.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true" >
    
        </ListView>
    
    </RelativeLayout>
    

    fragment2.xml

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/Fragment2"/>
    
    </RelativeLayout>
    

    fragment3.xml

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/Fragment3"/>
    
    </RelativeLayout>
    

    Fragment1.java

    public class Fragment1 extends Fragment {
        String[] titles={"A","B","C"};
        @Override
        public View onCreateView(
                LayoutInflater inflater, 
                ViewGroup container, 
                Bundle savedInstanceState){
            View rootView = inflater.inflate(R.layout.fragment1, container, false);
            ListView lv = (ListView) rootView.findViewById(R.id.listView1);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,titles);
            lv.setAdapter(adapter);
            return rootView;
        }   
    }
    

    Fragment2.java

    public class Fragment2 extends Fragment {
        @Override
        public View onCreateView(
                LayoutInflater inflater,
                ViewGroup container,
                Bundle savedInstanceState){
            View rootView = inflater.inflate(R.layout.fragment2, container, false);
            return rootView;
        }
    }
    

    Fragment3.java

    public class Fragment3 extends Fragment {
        @Override
        public View onCreateView(
                LayoutInflater inflater,
                ViewGroup container,
                Bundle savedInstanceState){
            View rootView = inflater.inflate(R.layout.fragment3, container, false);
            return rootView;
        }
    }
    

    在清单中添加主题

    android:theme="@style/Theme.AppCompat"
    

    捕捉

    【讨论】:

    • 我没有得到例外结果,请您详细说明您的答案。
    • @stiffler 一定给我一分钟
    • @stiffler 发布了一个示例。剩下的由你来修改
    • 这个解决方案很完美..我不知道为什么这个没有被接受。 +1 我这边。
    【解决方案2】:

    新版本的 v4 支持库(第 13 版)包含对导航抽屉模式的支持。
    查看以下Navigation Drawer 的教程链接,它提供了Navigation Drawer 的兼容性库以及其中的实现。

    1) Sherlock Navigation Drawer
    2) NavDrawerExampleAppCompat-v7
    3) Navigation Drawer in Android
    4)Create Navigation Drawer

    希望这会对您有所帮助。

    【讨论】:

    • 嗨,GrlsHU 以上所有示例都使用了片段,但我不想使用它们我有我的活动,你能提供任何关于它的材料吗...
    • 您必须使用 Fragment 来使用它。没有片段就不能使用它。
    【解决方案3】:

    Navigation Drawer 在 using DrawerLayout 中实现,如果不使用任何外部库,可在 Android 支持包中使用。所以它可以使用大约 API 级别 4 其中 Donut(1.6)。使用此链接了解更多信息DrawerLayout

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 2016-03-26
      相关资源
      最近更新 更多