Android DrawerLayout 的使用

jopen 9年前

Android L  Android Studio 1.4

从主视图左侧能抽出一个导航栏,效果图:

 点击后弹出新界面: 

新界面也可以抽出左侧导航栏

 

 

1.配置xml文件,指定根视图和左右抽屉视图

2.Activity中加载xml文件,设定UI动作

代码

首先配置 main_layout.xml 文件;用v4包里的DrawerLayout,指定一个FrameLayout作为根视图,后续可以把Fragment插入到这个FrameLayout中

抽屉视图是一个RelativeLayout,里面承载着几个UI,ListView用于装按钮,下面是退出按键

<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">      <!-- 指定Framelayout为根视图 -->      <FrameLayout          android:id="@+id/root_framelayout"          android:layout_width="match_parent"          android:layout_height="match_parent"></FrameLayout>        <!-- The left navigation drawer -->      <RelativeLayout          android:id="@+id/left_relative_drawer"          android:layout_width="240dp"          android:layout_height="match_parent"          android:layout_gravity="start"          android:background="#ffffcc"          android:clickable="true"><!-- clickable="true" 防止点击事件穿透 -->              <ImageButton              android:id="@+id/imagebtn_left_head"              android:layout_width="120dp"              android:layout_height="120dp"              android:layout_centerHorizontal="true"              android:layout_marginTop="20dp"              android:background="@drawable/littleboygreen"              android:scaleType="fitXY" />            <ListView              android:id="@+id/left_list"              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:layout_below="@id/imagebtn_left_head"              android:choiceMode="singleChoice"              android:divider="@android:color/transparent"              android:dividerHeight="10dp"              android:paddingTop="5dp"></ListView>            <Button              android:id="@+id/btn_left_exit"              android:layout_width="140dp"              android:layout_height="wrap_content"              android:layout_below="@id/left_list"              android:layout_centerInParent="true"              android:layout_marginTop="50dp"              android:background="@drawable/button_corner_shape"              android:text="退出应用"              android:textSize="20sp" />            <Button              android:id="@+id/btn_left_confirm"              android:layout_width="70dp"              android:layout_height="wrap_content"              android:layout_below="@id/left_list"              android:layout_marginLeft="30dp"              android:layout_marginTop="50dp"              android:background="@drawable/button_corner_shape"              android:text="退出"              android:textSize="20sp" />            <Button              android:id="@+id/btn_left_cancel"              android:layout_width="70dp"              android:layout_height="wrap_content"              android:layout_below="@id/left_list"              android:layout_marginLeft="40dp"              android:layout_marginTop="50dp"              android:layout_toRightOf="@id/btn_left_confirm"              android:background="@drawable/button_cancel_corner_shape"              android:text="取消"              android:textSize="20sp" />        </RelativeLayout>      </android.support.v4.widget.DrawerLayout>

在MainActivity.java的onCreate方法中加载这个layout

setContentView(R.layout.main_layout);
</div> </td> </tr> </tbody> </table> </div> </div> </div>

主视图就只有一张背景,新写一个MainFragment加载进去

MainFragment.java

public class MainFragment extends Fragment {        ......        private Toolbar toolbar;        ......        @Nullable      @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {          View rootView = inflater.inflate(R.layout.main_relativelayout, container,false);        /* 这里设置UI,设置按钮监听等等 */      /* 为防止单调,显示放屏幕分辨率和屏幕方向 */          return rootView;      }        /* 屏幕分辨率 */      private String getScreenRatio(){          StringBuilder ratio = new StringBuilder("");          mDisplay = ((WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE))                  .getDefaultDisplay();/* 先getActivity */          DisplayMetrics mDisplayMetrics = new DisplayMetrics();          mDisplay.getMetrics(mDisplayMetrics);          mDisplay.getSize(mCurrentDisplaySize);/* 竖屏Point(1536, 1964) 横屏Point(2048, 1452) */          Log.d("rust","mCurrentDisplaySize  "+ mCurrentDisplaySize);          int screenWidth = mDisplayMetrics.widthPixels;          int screenHeight = mDisplayMetrics.heightPixels;          ratio.append(screenWidth);          ratio.append(" x ");          ratio.append(screenHeight);          return ratio.toString();      }      /* 获取屏幕方向 */      private void getOrientation() {          config = getResources().getConfiguration();/* 检查屏幕方向 */          if (config.orientation == Configuration.ORIENTATION_LANDSCAPE){              screenOrientation = "LANDSCAPE";          } else if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {              screenOrientation = "PORTRAIT";          } else {              screenOrientation = "Unknow";          }      }    }

回到MainActivity.java的onCreate方法,把MainFragment加载进去

mainFragment = new MainFragment();/* 指定一个单独的Fragment */       ......       final FragmentManager fragmentManager = getFragmentManager();/* 加载到root容器 */     fragmentManager.beginTransaction().add(R.id.root_framelayout, mainFragment).commit();

同样在MainActivity.java的onCreate方法中加载一下导航栏

/* 左抽屉 */          leftDrawer = (RelativeLayout) findViewById(R.id.left_relative_drawer);            /* 左列表在左抽屉里 */          leftList = (ListView) leftDrawer.findViewById(R.id.left_list);            /* 适配器装载数据;即初始化导航列表;这里使用SimpleAdapter,加载自定义的LinearLayout作为按钮 */          contentLeftAdapter = new SimpleAdapter(this, leftDrawerListData(),                  R.layout.list_item_linearlayout, new String[]{"image","text"},                  new int[]{R.id.image_left_item,R.id.tv_left_item});            leftList.setAdapter(contentLeftAdapter);            /* 为list设置ClickListener;DrawerOnItemClickListener定义在下面*/          leftList.setOnItemClickListener(new DrawerOnItemClickListener());            imageBtnLeft.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  fragmentManager.beginTransaction()                          .replace(R.id.root_framelayout, mainFragment)                          .commit();                  mDrawerLayout.closeDrawer(leftDrawer);              }          });            btnExit.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  btnConfirmExit.setVisibility(View.VISIBLE);                  btnCancelExit.setVisibility(View.VISIBLE);                  btnExit.setVisibility(View.INVISIBLE);              }          });            btnCancelExit.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {                  btnCancelExit.setVisibility(View.INVISIBLE);                  btnConfirmExit.setVisibility(View.INVISIBLE);                  btnExit.setVisibility(View.VISIBLE);              }          });            btnConfirmExit.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View v) {  //                finish();                  android.os.Process.killProcess(android.os.Process.myPid());              }          });

往listview中添加内容的方法

private List<Map<String, Object>> leftDrawerListData(){          List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();          Map<String, Object> map = new HashMap<String, Object>();          map.put("image", R.drawable.orange01);          map.put("text", "橘子");          list.add(map);            map = new HashMap<String, Object>();          map.put("image", R.drawable.sixtraveltransportation);          map.put("text", "路标");          list.add(map);            map = new HashMap<String, Object>();          map.put("image", R.drawable.traintraveltransportation);          map.put("text", "火车");          list.add(map);            map = new HashMap<String, Object>();          map.put("image", R.drawable.ecologytree);          map.put("text", "树苗");          list.add(map);            map = new HashMap<String, Object>();          map.put("image", R.drawable.ecology);          map.put("text", "插头");          list.add(map);            return list;      }

导航栏按钮监听

private class DrawerOnItemClickListener implements AdapterView.OnItemClickListener{          @Override          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              seleteItem(position);/* 按钮选择 */          }      }        private void seleteItem(int position){          leftList.setItemChecked(position, true);            Fragment newFragment = new ContentFragment();/* new 一个子fragment */          Bundle args = new Bundle();          args.putInt(ContentFragment.ARG_SHOW_FRAGMENT,position);          newFragment.setArguments(args);/* 装载数据 */            FragmentManager childFragmentManager = getFragmentManager();          childFragmentManager.beginTransaction()                  .replace(R.id.root_framelayout, newFragment)                  .commit();/* 替换当前fragment */            /* 最后关闭左侧抽屉 */          mDrawerLayout.closeDrawer(leftDrawer);      }

点击一下导航栏的按钮,就会把原来的MainFragment替换掉

 

DrawerLayout往往和Fragment结合起来使用;布局界面可以更丰富和灵活

如果跳到另一个Activity,就抽不出MainActivity的DrawerLayout

 

来自:http://www.cnblogs.com/rustfisher/p/4906502.html