以编程方式构建导航抽屉

时间:2016-06-16 17:34:57

标签: android android-layout navigation-drawer drawerlayout programmatically-created

我有一个DrawerLayout,它使用2个布局。

  1. 为主要内容。 (RelativeLayout的)
  2. 抽屉窗格。 (的LinearLayout)
  3. 我需要创建所有DYNAMCALLY,因此不必使用XML。

    这是创建drawerPane的代码:

    public class Test2 extends AppCompatActivity{
    
        ListView myList;
        DrawerLayout drawerLayout;
    
        LinearLayout drawerPane;
        RelativeLayout content;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            myList=new ListView(this);
    
            drawerLayout=new DrawerLayout(this);
    
            DrawerLayout.LayoutParams drawerLayout_params=new DrawerLayout.LayoutParams(280, DrawerLayout.LayoutParams.MATCH_PARENT);
    
            drawerLayout.setId(0);
    
            drawerPane=new LinearLayout(this);
            drawerPane.setGravity(Gravity.START);
            drawerPane.setClickable(true);
    
            myList=new ListView(this);
    
            myList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    
            LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(280,LinearLayout.LayoutParams.MATCH_PARENT);
            lp.gravity=Gravity.START;
    
            drawerPane.setLayoutParams(lp);
    
            drawerPane.addView(myList,new ListView.LayoutParams(280,ListView.LayoutParams.MATCH_PARENT));
    
            drawerPane.setGravity(Gravity.START);
            drawerPane.setOrientation(LinearLayout.VERTICAL);
    
            setContentView(drawerLayout,drawerLayout_params);
    
            content=new RelativeLayout(this);
    
            drawerLayout.addView(content,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            drawerLayout.addView(drawerPane,lp);
    
            LinkedList<String> list=new LinkedList<>();
    
            list.add("Item #1");
            list.add("Item #2");
            list.add("Item #3");
    
            myList.setAdapter(new My_Adapter<String>(this,R.layout.drawer_item,list) {
                @Override
                protected void set(String item, View customView) {
    
                    TextView title=(TextView)customView.findViewById(R.id.title);
                    TextView subTitle=(TextView)customView.findViewById(R.id.subTitle);
    
                    title.setText(item);
                    subTitle.setText(item);
                }
            });
        }
    }
    

    我使用My_Adapter自定义类作为ListView的适配器:

    public abstract class My_Adapter<T> extends BaseAdapter {
    
        private int customLayoutID;
    
        private Context myContext;
    
        private Collection<T> listValues;
        private T[] arrayValues;
    
        private final boolean listMode;
        private final boolean arrayMode;
    
        public My_Adapter(Context context,int layoutID, T[] values) {
    
            arrayMode=true;
            listMode=false;
    
            myContext=context;
            arrayValues=values;
            customLayoutID=layoutID;
        }
    
        public My_Adapter(Context context,int layoutID, Collection<T> values) {
    
            listMode=true;
            arrayMode=false;
    
            myContext=context;
            listValues=values;
            customLayoutID=layoutID;
        }
    
        @Override
        public int getCount() {
    
            if (listMode){
    
                return listValues.size();
            }
            else if (arrayMode){
    
                return arrayValues.length;
            }
            else return -1;
        }
    
        @Override
        public T getItem(int position) {
    
            if (listMode){
    
                return ((List<T>) listValues).get(position);
            }
            else if (arrayMode){
    
                return arrayValues[position];
            }
            else return null;
        }
    
        @Override
        public long getItemId(int position) {
    
            return position;
        }
    
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            LayoutInflater inflater= LayoutInflater.from(myContext);
    
            View myView= inflater.inflate(customLayoutID,parent,false);
    
            T item=getItem(position);
    
            set(item,myView);
    
            return myView;
        }
    
        protected abstract void set(T item, View customView);
    }
    

    使用此代码,这就是应用程序的样子:

    Application preview

    这是drawer_item.xml文件:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dp"
        android:paddingBottom="10dp">
    
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:gravity="center_vertical"
            android:textColor="@color/abc_primary_text_material_dark"
            android:text="Line 1"
            android:textStyle="bold" />
    
        <TextView android:id="@+id/subTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Line 2"
            android:textColor="#717171"
            android:layout_below="@+id/title"
            android:layout_alignRight="@+id/title"
            android:layout_alignEnd="@+id/title" />
    
    </RelativeLayout>
    

    修改/更新

    我希望得到与以下xml代码相同的结果。 看看&#34; LAYOUT_GRAVITY&#34;对于LinearLayout。

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <!-- The main content view -->
        <RelativeLayout
            android:id="@+id/mainContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
    
        </RelativeLayout>
    
        <!-- The navigation drawer -->
        <LinearLayout
            android:layout_width="280dp"
            android:layout_height="match_parent"
            android:id="@+id/drawerPane"
            android:layout_gravity="start"
            android:clickable="true"
            android:orientation="vertical">
    
            <!-- Profile Box -->
    
            <RelativeLayout
                android:id="@+id/profileBox"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:background="@color/material_blue_grey_900"
                android:padding="8dp" >
    
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="42dp"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="15dp"
                    android:orientation="vertical" >
    
                    <TextView
                        android:id="@+id/userName"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="ElektroFR"
                        android:textColor="#fff"
                        android:textSize="16sp"
                        android:textStyle="bold" />
    
                    <TextView
                        android:id="@+id/desc"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/userName"
                        android:layout_marginTop="4dp"
                        android:text="View Profile"
                        android:textColor="#fff"
                        android:textSize="12sp" />
                </LinearLayout>
            </RelativeLayout>
    
            <!-- List of Actions (pages) -->
            <ListView
                android:id="@+id/navList"
                android:layout_width="280dp"
                android:layout_height="match_parent"
                android:layout_below="@+id/profileBox"
                android:choiceMode="singleChoice"
                android:background="@color/bright_foreground_disabled_material_light" />
    
        </LinearLayout>
    
    </android.support.v4.widget.DrawerLayout>
    

3 个答案:

答案 0 :(得分:0)

在将视图添加到父组之前,不要设置视图的布局参数,而是使用除View之外还带有LayoutParam参数的addView版本。

另外,FWIW,不建议使用项目ID的位置值。

答案 1 :(得分:0)

<强>解 感谢这个问题答案!:

SOLUTION

您必须为抽屉使用的每个视图使用DrawerLayout.LayoutParams!

  1. the drawerpane
  2. listView
  3. 这是最终代码:

    包elektro_fr.newapplication;

    public class Test2 extends AppCompatActivity{
    
        ListView myList;
        DrawerLayout drawerLayout;
    
        LinearLayout drawerPane;
        RelativeLayout content;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            myList=new ListView(this);
    
            drawerLayout=new DrawerLayout(this);
    
            DrawerLayout.LayoutParams drawerLayout_params=new DrawerLayout.LayoutParams(My_AndroidTools.DisplayTools.getPixelsDimension(getResources(),180), DrawerLayout.LayoutParams.MATCH_PARENT);
            drawerLayout_params.gravity=Gravity.START;
    
            drawerLayout.setId(0);
    
            drawerPane=new LinearLayout(this);
            drawerPane.setGravity(Gravity.START);
            drawerPane.setClickable(true);
    
            myList=new ListView(this);
    
            myList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    
            drawerPane.setLayoutParams(drawerLayout_params);
    
            drawerPane.addView(myList,drawerLayout_params);
    
            drawerPane.setOrientation(LinearLayout.VERTICAL);
    
            setContentView(drawerLayout,drawerLayout_params);
    
            content=new RelativeLayout(this);
    
            drawerLayout.addView(content,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            drawerLayout.addView(drawerPane,drawerLayout_params);
    
            LinkedList<String> list=new LinkedList<>();
    
            list.add("Item #1");
            list.add("Item #2");
            list.add("Item #3");
    
            myList.setAdapter(new My_Adapter<String>(this,R.layout.drawer_item,list) {
                @Override
                protected void set(String item, View customView) {
    
                    TextView title=(TextView)customView.findViewById(R.id.title);
                    TextView subTitle=(TextView)customView.findViewById(R.id.subTitle);
    
                    title.setText(item);
                    subTitle.setText(item);
                }
            });
        }
    }
    

答案 2 :(得分:0)

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

    //=========================Adding Toolbar in android layout======================================
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);

    //=========================Toolbar End============================================================


    /***************************************************************************************
     * Navigation Drawer Layout
     *
     ***************************************************************************************/
    // drawer layout instance to toggle the menu icon to open
    // drawer and back button to close drawer
    drawerLayout = findViewById(R.id.draw_layout);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close);

    // pass the Open and Close toggle for the drawer layout listener
    // to toggle the button
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();

    mNavigationView =  findViewById(R.id.nav_view);
    mNavigationView.setNavigationItemSelectedListener(this);

    // to make the Navigation drawer icon always appear on the action bar
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
   /***************************************************************************************
    * Navigation Drawer Layout
    *
    ***************************************************************************************/


}

使用此链接: https://timxn.com/en/programmatically-add-navigation-drawer-android