2014-02-10 49 views
6

我想在我的主要活动中将此xml转换为java,输出为导航抽屉。我只需要在这部分帮助,我完成了其余部分。如何以编程方式创建DrawerLayout

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

我需要一些帮助来定制列表视图的布局宽度和布局重力代码。

+2

XML布局使用情况如何? – gunar

+0

我想在代码中创建它,我在xml中不感兴趣 – user289175

回答

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