DrawerLayout抽屉布局的使用 最简单的侧滑菜单实现

DrawerLayout抽屉布局的使用 最简单的侧滑菜单实现_第1张图片

之前项目中遇到需要实现侧滑菜单,自己动手写真是费劲,各种手势判断,各种事件监听,而且效果不是太好,后来知道DrawerLayout实现侧滑真的很方便,用法也非常简单。

DrawerLayout是V4包中的内容,使用如下

小弟文笔不好,直接附上代码:

1.首先定义Xml布局,



    

    
    
    
	
        

2.java中主布局代码

package com.example.drawerlayout;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

	private DrawerLayout drawerLayout;
	private ListView leftDrawer;
	private ArrayAdapter adapter;
	private final String[] items = new String[] { "选项一:", "选项二:", "选项三:",
			"选项4:", "选项5:", "选项6:" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		leftDrawer = (ListView) findViewById(R.id.drawer_left);
		adapter = new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, items) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				// 设置背填充内容背景色
				TextView tView = (TextView) super.getView(position,
						convertView, parent);
				tView.setTextColor(Color.BLACK);
				return super.getView(position, convertView, parent);
			}
		};
		leftDrawer.setAdapter(adapter);
		leftDrawer.setBackgroundColor(Color.WHITE);

		// 设置选择模式为单条选中
		leftDrawer.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		leftDrawer.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView parent, View view, int pos,
					long id) {
				leftDrawer.setItemChecked(pos, true);
				NumerFragment frag = NumerFragment.createNumerFragment(pos);
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.content_view, frag).commit();
				// 关闭所有打开的抽屉
				drawerLayout.closeDrawers();
			}
		});

		// 通过代码:根据重力方向打开指定抽屉
		drawerLayout.openDrawer(Gravity.LEFT);
		// 设置抽屉阴影
		// drawerLayout.setDrawerShadow(R.drawable.ic_launcher, Gravity.LEFT);
		// 设置抽屉空余处颜色
		drawerLayout.setScrimColor(Color.BLUE);
		// 设置抽屉锁定模式 LOCK_MODE_LOCKED_OPEN:锁定 无法滑动; 只能通过代码取消锁定
		// drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
	}
}




你可能感兴趣的:(Android基础)