如何以编程方式创建DrawerLayout

6

我希望能够在我的主活动中将这个XML文件转换为Java代码,输出导航抽屉。我只需要在这部分获得帮助,其余部分我已经完成。

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<FrameLayout
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

<ListView
    android:id="@+id/drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#FFF"
    android:choiceMode="singleChoice"/>

我希望能够用Java代码编写上述XML,如何实现?

提前致谢。

更新

final DrawerLayout drawer = new android.support.v4.widget.DrawerLayout(this);
     final FrameLayout fl = new FrameLayout(this);
     fl.setId(CONTENT_VIEW_ID);
     final ListView navList = new ListView (this);

     drawer.addView(fl, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
     drawer.addView(navList);

     setContentView(drawer);

我需要一些帮助,以编码方式自定义listview的布局宽度和布局重力。


2
XML布局的使用出了什么问题? - gunar
我想用代码创建它,我对XML不感兴趣。 - user289175
1个回答

7

问题的提问者在编辑问题时回答了自己的问题,并转换成了社区wiki答案。请参见“没有答案但评论中解决的问题(或在聊天中扩展)”

提问者写道:

问题已经解决,以下是完整代码

final DrawerLayout drawer = new android.support.v4.widget.DrawerLayout(this);
     final FrameLayout fl = new FrameLayout(this);
     fl.setId(CONTENT_VIEW_ID);
     final ListView navList = new ListView (this);

     DrawerLayout.LayoutParams lp = new DrawerLayout.LayoutParams(
            100 , LinearLayout.LayoutParams.MATCH_PARENT);

     lp.gravity=Gravity.START;


     navList.setLayoutParams(lp); 

     drawer.addView(fl, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
     drawer.addView(navList);

     setContentView(drawer);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接