如何以编程方式创建DrawerLayout

时间:2014-02-10 22:46:50

标签: android listview drawerlayout

我想在我的主要活动中将这个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,How?

提前致谢

更新

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的布局宽度和布局重力。

1 个答案:

答案 0 :(得分:7)

(在问题编辑中由OP回答。转换为社区维基答案。请参阅Question with no answers, but issue solved in the comments (or extended in chat)

OP写道:

  

我解决了,这是完整的代码

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