Android DrawerLayout实现抽屉效果实例代码

 官网:https://developer.android.com/training/implementing-navigation/nav-drawer.html

贴上主要的逻辑和布局文件:

activity_main.xml

 
 
   
   
   
   
   
 

这里需要注意一下:content主界面一定要定义在drawer的前面,另外,Android:layout_gravity="start"(从左往右)或者android:layout_gravity="end"(从右往左),这个属性是必须要定义的,不然出现下面的异常:

Android DrawerLayout实现抽屉效果实例代码_第1张图片

MainActivity.java

package com.jackie.drawerlayoutdemo; 
import android.os.Bundle; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 
public class MainActivity extends AppCompatActivity { 
  private String mTitle; 
  private DrawerLayout mDrawerLayout; 
  private ListView mDrawerMenu; 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    initView(); 
    initData(); 
    //默认打开抽屉 
    mDrawerLayout.openDrawer(mDrawerMenu); 
  } 
  private void initView() { 
    mTitle = getResources().getString(R.string.app_name); 
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
    mDrawerMenu = (ListView) findViewById(R.id.drawer_menu); 
  } 
  private void initData() { 
    //数组定义在xml 文件中 
    String[] items = getResources().getStringArray(R.array.left_drawer_items); 
    ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1); 
    adapter.addAll(items); 
    mDrawerMenu.setAdapter(adapter); 
    mDrawerMenu.setSelection(0); 
    //设置点击item事件 
    mDrawerMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView parent, View view, int position, long id) { 
        mTitle = ((TextView) view).getText().toString(); 
        switchFragment(); 
        mDrawerLayout.closeDrawer(mDrawerMenu); 
        mDrawerMenu.setSelection(position); 
      } 
    }); 
  } 
  private void switchFragment() { 
    getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, new ItemFragment(mTitle)).commit(); 
    getSupportActionBar().setTitle(mTitle); 
  } 
} 

效果图如下:

Android DrawerLayout实现抽屉效果实例代码_第2张图片

以上所述是小编给大家介绍的Android DrawerLayout实现抽屉效果实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

你可能感兴趣的:(Android DrawerLayout实现抽屉效果实例代码)