Android set navigation drawer list to open exact half of the screen for all device screen

Mayur Raval picture Mayur Raval · Jan 10, 2014 · Viewed 30.1k times · Source

I want to open the drawerlist to the half of the screen for all different device. i tried hard coded values for layout_margineleft 200dp or 100dp to the drawerlist. but it doesn't work in all device it different from device to device. so how can i maintain the exactly half of the screen for drawerlist. i also tried various function like setLeft(int) etc.but some of them doesn't work due to i use minimum version 8. So please help me. thanks in advance.

    mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) view.findViewById(R.id.top_sectionlist);

xml for that:

<?xml version="1.0" encoding="utf-8"?>

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="match_parent"
 android:layout_height="fill_parent"
 android:layout_margin="@dimen/top_news_linear_margin"
 android:background="@color/news_list_divider_color"
 android:orientation="vertical"
android:padding="@dimen/top_news_linear_padding" >

</RelativeLayout>

<ListView
 android:id="@+id/drawer_list"
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"
 android:layout_gravity="right"
 android:layout_alignParentTop="true"
 android:background="@color/setting_background"
 android:cacheColorHint="@android:color/transparent"
 android:choiceMode="singleChoice"
 android:divider="@color/news_list_divider_color"
 android:dividerHeight="@dimen/news_list_divider_height"
 />

</android.support.v4.widget.DrawerLayout>

Answer

Gopal Gopi picture Gopal Gopi · Jan 10, 2014

set the width for ListView dynamically...

    mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) view.findViewById(R.id.top_sectionlist);

    int width = getResources().getDisplayMetrics().widthPixels/2;
    DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerList.getLayoutParams();
    params.width = width;
    mDrawerList.setLayoutParams(params);