繁体   English   中英

以编程方式构建导航抽屉

[英]Programmatically build Navigation Drawer

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

  1. 为主要内容。 (相对布局)
  2. 抽屉窗格。 (线性布局)

我需要动态创建所有内容,因此不必使用 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);
}

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

应用预览

这是 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 代码相同的结果。 查看 LinearLayout 的“LAYOUT_GRAVITY”。

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

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

此外,FWIW,不建议使用项目 id 的位置值。

解决这个问题的答案!:

解决方案

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

  1. 抽屉板
  2. 列表视图

这是最终的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM