How to create DrawerLayout programmatically

做~自己de王妃 提交于 2019-12-04 08:42:22

问题


I would like to translate this xml to java in my main activity, the output is navigation drawer. I need help only in this part, I finished the remaining parts.

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

I would like to write above xml in java code, How ?

Thanks in advance

Update

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

I need little help to customise listview's layout width and layout gravity in code.


回答1:


(Answered by the OP in a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

I solved, here is the complete code

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


来源:https://stackoverflow.com/questions/21689487/how-to-create-drawerlayout-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!