我们知道google 的android 的design 包中新增了许多的新特性和比较炫的布局的封装,而且通过新版本的androidstudio我们可以直接直接创建这些带功能的工程。极其的方便。看一下有哪些:
可以看到样式非常的多,非常方便。其中Naviogation Drawer 就是我们今天需要描述的。
今天我们针对侧滑的这个design通过源码简单分析一下之间的关联和实现的方式。首先我们来看一下gif图:
嗯就是这个效果。接下来我们看看谷歌到底帮我们做了哪些操作呢。看代码:
先看Activity 中的代码:
package com.szh.designsimple;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//这句话创建toolbar右侧菜单的关键 只有这样才会执行onCreateOptionsMenu,才会创建菜单
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//创建左侧toolbar按钮并且关联导航栏
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.action_settings, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
// NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
// navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
//返回按钮的监听
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//创建菜单
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//菜单中item的选中事件
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return