侧边栏 DrawerLayout布局使用教程

首先我们使用DrawerLayout布局:
xmlns:android=“http://schemas.android.com/apk/res/android”
android:id="@+id/draw_layout"
android:layout_width=“match_parent”
android:layout_height=“match_parent”>

DrawerLayout布局内用两个大布局即可实现侧边栏的效果.

我们可以看到以下代码中,首先使用了RelativeLayout布局,这是主页面的布局,接下来LinearLayout为侧边栏的布局.注意LinearLayout布局内需要设置android:layout_gravity=“start” 也可以设置为end.即可实现

    


    
    

    

    

布局就看到这里,
下面我们来看代码处理:
首先我们要实现View.OnClickListener接口,接下来我们查找控件,设置监听,要提前建好Fragment
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private ImageView img_left;
private TextView xList_left;
private TextView tab_left;
private DrawerLayout draw_layout;
private AFragment aFragment;
private BFragment bFragment;
private FragmentManager manager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    initData();
}
//创建Fragment对象
private void initData() {
    aFragment = new AFragment();
    bFragment = new BFragment();
}
//获取控件 设置监听
private void initView() {
    img_left = (ImageView) findViewById(R.id.img_left);
    img_left.setOnClickListener(this);

    xList_left = (TextView) findViewById(R.id.xList_left);
    xList_left.setOnClickListener(this);

    tab_left = (TextView) findViewById(R.id.tab_left);
    tab_left.setOnClickListener(this);

    draw_layout = (DrawerLayout) findViewById(R.id.draw_layout);
    //获取Fragment管理类
    manager = getSupportFragmentManager();
}
//监听事件
@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.img_left:
            Toast.makeText(MainActivity.this,"您的头像",Toast.LENGTH_SHORT).show();
            break;
        case R.id.xList_left:
            manager.beginTransaction().replace(R.id.frag_content,aFragment).commit();
            //不要忘记closeDrawers();
            draw_layout.closeDrawers();
            break;
        case R.id.tab_left:
            manager.beginTransaction().replace(R.id.frag_content,bFragment).commit();
            draw_layout.closeDrawers();
            break;
    }

}

}
注意不要忘记closeDrawers()以及break;
DrawerLayout实现侧边栏效果比较简单,看到这里,您应该已经明白了

你可能感兴趣的:(侧边栏 DrawerLayout布局使用教程)