主页面布局,根布局是drawlayout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/drawlayout">
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@drawable/ic_launcher_background">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
****activity内容:***
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件对象
initView();
//初始化ActionBar
intiActionBar();
}
//设置点击左上角,能够弹出侧边框菜单
private void intiActionBar() {
//获取一个actionbar对象
ActionBar actionBar=getSupportActionBar();
//给左上角一张图片,默4.0,true
actionBar.setDisplayHomeAsUpEnabled(true);
//有一类提供了绑定drawlayout功能
toggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
// **(R.string.open,R.string.close在strings.xml中自定义)**
//drawerlayout和actionbar关联
toggle.syncState();//同步状态
drawerLayout.addDrawerListener(toggle);
}
private void initView() {
drawerLayout=findViewById(R.id.drawlayout);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
//设置左上角按钮具备点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}