Android 使用DrawerLayout同时实现双侧滑板

菜单文件

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.actiontabbar.DrawerToggleActivity" >

    <item android:id="@+id/action_search"
        	android:orderInCategory="100"
 			android:title="@string/action_search"  
 			app:actionViewClass="android.support.v7.widget.SearchView" 
 			app:showAsAction="ifRoom"
 />
  
     <item
        android:id="@+id/action_menus"
        android:orderInCategory="100"
        android:icon="@drawable/fm_list_item_program_icon"
        android:title="@string/action_camera"
        app:showAsAction="ifRoom"/>
     <item
        android:id="@+id/action_camera"
        android:orderInCategory="100"
        android:icon="@drawable/ofm_camera_icon"
        android:title="@string/action_camera"
        app:showAsAction="never"/>
     <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:icon="@drawable/ofm_setting_icon"
        android:title="@string/action_settings"
        app:showAsAction="never"/>

</menu>

布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <RelativeLayout
        android:id="@+id/main_content_frame_parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent" >

        <!-- 下层显示的主要内容 -->

        <Button
            android:id="@+id/id_left_openBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="35dp"
            android:text="Left Menu" />

        <Button
            android:id="@+id/id_right_openBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/id_left_openBtn"
            android:layout_marginTop="17dp"
            android:text="Right Menu" />
    
    </RelativeLayout>
    <!-- 左侧滑动栏 -->

    <RelativeLayout
        android:id="@+id/main_left_drawer_layout"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#33000000"
         android:focusable="true"
        android:focusableInTouchMode="true"
        android:paddingTop="50dp" >
    </RelativeLayout>
    <!-- 右侧滑动栏 -->

    <RelativeLayout
        android:id="@+id/main_right_drawer_layout"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="#33000000"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:paddingTop="50dp" >
    </RelativeLayout>

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

代码文件

public class DoubleDrawLayout extends Activity implements OnClickListener, OnTouchListener {

	
	private Button mLeftMenuBtn;
	private Button mRightMenuBtn;
	private DrawerLayout mDrawerLayout;
	private RelativeLayout leftMenulayout;
	private RelativeLayout rightMessagelayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.double_drawerlayout);
		
		mLeftMenuBtn = (Button)findViewById(R.id.id_left_openBtn);
		mRightMenuBtn = (Button)findViewById(R.id.id_right_openBtn);
		
		mDrawerLayout = (DrawerLayout)findViewById(R.id.main_drawer_layout);
		mDrawerLayout.setScrimColor(0x00000000);
		
		initEvent();
		initLeftLayout();
		initRightLayout();
		
		
		mLeftMenuBtn.setOnClickListener(this);
		mRightMenuBtn.setOnClickListener(this);
		
		leftMenulayout.setOnTouchListener(this);
		rightMessagelayout.setOnTouchListener(this);
	}
	
	
	public void initLeftLayout(){


        //设置透明

        //左边菜单

       leftMenulayout = (RelativeLayout) findViewById(R.id.main_left_drawer_layout);
       View view2 = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
       TextView tv = (TextView)view2.findViewById(android.R.id.text1);
       tv.setText("左边测试菜单");
       leftMenulayout.addView(view2);
        tv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				Toast.makeText(DoubleDrawLayout.this, "Left", Toast.LENGTH_SHORT).show();
			}
		});
    }

    public void initRightLayout(){

        //左边菜单
        rightMessagelayout = (RelativeLayout) findViewById(R.id.main_right_drawer_layout);
        View view = getLayoutInflater().inflate(android.R.layout.simple_list_item_1, null);
        TextView tv = (TextView)view.findViewById(android.R.id.text1);
        tv.setText("右边测试菜单");
        rightMessagelayout.addView(view);
        tv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				Toast.makeText(DoubleDrawLayout.this, "Right", Toast.LENGTH_SHORT).show();
			}
		});
    }

    private void initEvent() {

    	mDrawerLayout.setDrawerListener(new DrawerListener() {
			
			@Override
			public void onDrawerStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onDrawerSlide(View arg0, float arg1) {
				
			}
			
			@Override
			public void onDrawerOpened(View arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onDrawerClosed(View arg0) {
				// TODO Auto-generated method stub
				
			}
		});

    }

        //左边菜单开关事件

    public void openLeftLayout() {

        if (mDrawerLayout.isDrawerOpen(leftMenulayout)) {

        	mDrawerLayout.closeDrawer(leftMenulayout);

        } else {

        	mDrawerLayout.openDrawer(leftMenulayout);
        }

    }

    // 右边菜单开关事件

    public void openRightLayout() {

        if (mDrawerLayout.isDrawerOpen(rightMessagelayout)) {

        	mDrawerLayout.closeDrawer(rightMessagelayout);

        } else {

        	mDrawerLayout.openDrawer(rightMessagelayout);

        }

    }

	@Override
	public void onClick(View v) {
		
		
		switch (v.getId()) {
			case R.id.id_left_openBtn:
				openLeftLayout();
				break;
			case R.id.id_right_openBtn:
				openRightLayout();
				break;
	
			default:
				break;
		}
		
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return true;//阻止事件多重分发
	}
}

-----------------------------------------2015-05-05日更新,实现左右可滑动单面板----------------------------------------------------

<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
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
public class DrawerActivity extends ActionBarActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;

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

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);//抽屉里的view

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(new ColorDrawable(0x99f20000), GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_expandable_list_item_1, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
       // mDrawerLayout.setScrimColor(0x9901f201);
        // enable ActionBar app icon to behave as action to toggle nav drawer   需要api level 11
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//给home icon的左边加上一个返回的图标
        getSupportActionBar().setHomeButtonEnabled(true); //需要api level 14  使用home-icon 可点击

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(//v4控件  actionbar上的抽屉开关
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.comm_ic_main_top_menu,  /* nav drawer image to replace 'Up' caret */		//上一级图标 返回图标
                R.string.slider_open,  /* "open drawer" description for accessibility */
                R.string.slider_close  /* "close drawer" description for accessibility */
                ) {
        	@SuppressLint("NewApi")
            public void onDrawerClosed(View view) {//抽屉关闭后
            	getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
            @SuppressLint("NewApi")
             public void onDrawerOpened(View drawerView) {//抽屉打开后
            	getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
            
            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
            	
        		
            	if ( item.getItemId() == android.R.id.home) {//actionbar上的home icon
                    LayoutParams lp = (LayoutParams) mDrawerList.getLayoutParams();
            		if(lp.gravity!=GravityCompat.START)
            		{
            			lp.gravity = GravityCompat.START;
            			mDrawerList.setLayoutParams(lp);
            		}
            		
            		if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
                         mDrawerLayout.closeDrawer(GravityCompat.START);//关闭抽屉
                     } else {
                         mDrawerLayout.openDrawer(GravityCompat.START);//打开抽屉
                     }
                    return true;
                }
            	else if(item.getItemId()==R.id.action_menus)
                {
            		//END即gravity.right 从右向左显示   START即left  从左向右弹出显示
            		LayoutParams lp = (LayoutParams) mDrawerList.getLayoutParams();
            		if(lp.gravity!=GravityCompat.END)
            		{
            			lp.gravity = GravityCompat.END;
            			mDrawerList.setLayoutParams(lp);
            		}
                    if (mDrawerLayout.isDrawerVisible(GravityCompat.END)) {
                        mDrawerLayout.closeDrawer(GravityCompat.END);//关闭抽屉
                    } else {
                        mDrawerLayout.openDrawer(GravityCompat.END);//打开抽屉
                    }
            		return true;
                }
                return false;
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);//设置抽屉监听

        if (savedInstanceState == null) {
//            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {//加载menu  sdk3.0以后menu包含在actionbar中
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.toggle_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_search).setVisible(!drawerOpen);//search的显示与drawer的显示相反
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch(item.getItemId())
        {
        case R.id.action_search:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, "invalide", Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }
    
  //内容区显示PlanetFragment
    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
//        mDrawerList.setItemChecked(position, true);
//        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
    	mDrawerTitle = title;
        getSupportActionBar().setTitle(mDrawerTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];
            //查找出 res-drawable资源的id
            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.section_image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }
}

Android 使用DrawerLayout同时实现双侧滑板

你可能感兴趣的:(Android 使用DrawerLayout同时实现双侧滑板)