一.简介:
本文只是写了个简单的侧边栏的demo,界面基本没有做处理,实现过程中添加了右划对主界面按钮点击事件的拦截,效果图:
二.实现:
1.activity_main.xml:
<?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/colorAccent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:onClick="click" android:text="主界面" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="left" android:background="#fff" android:orientation="vertical"> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="@null" /> </LinearLayout> </android.support.v4.widget.DrawerLayout>2.MainActivity类:
public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private String[] mLeftMenu = {"头像", "设置", "我的"}; private DrawerLayout mDrawerLayout; private ListView mListView; //滑动的其实X坐标。 private float startX; //如果侧边栏显示拦截按钮的监听。 private boolean isScrollOpen = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mListView = (ListView) findViewById(R.id.listview); mListView.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, mLeftMenu)); mDrawerLayout.openDrawer(Gravity.LEFT); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDrawerLayout.closeDrawer(Gravity.LEFT); showMessage("您点击了" + mLeftMenu[position]); } }); } public void click(View view) { showMessage("您点击了主页面"); } private void showMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.e(TAG, "dispatchTouchEvent: " ); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: isScrollOpen = false; startX = ev.getX(); break; case MotionEvent.ACTION_MOVE: if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT) && ev.getX() - startX > 10) { mDrawerLayout.openDrawer(Gravity.LEFT); isScrollOpen = true; } break; case MotionEvent.ACTION_UP: if(isScrollOpen){ return true; } break; } return super.dispatchTouchEvent(ev); } }3.drawer_list_item.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="45dp" android:gravity="center"> </TextView>
三.注意事项:
1.xml中DrawerLayout包裹的布局设置android:layout_gravity="left"表示在左边DrawerLayout的openDrawer()和closeDrawer();方法传入要打开和关闭左边还是右边。
demo下载地址:点击打开链接