安卓中侧滑菜单栏DrawerLayout的使用(新版安卓2019)
安卓开发中首次使用滑动菜单,所看的书籍使用的旧版本的Android studio,学习中遇到很多困难,多次闪退,以下是成功的版本:
- 在app -> src -> main -> res -> values 中的“styles.xml”文档中的
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
这句话中的DarkActionBar来控制手机app中的最上方导航栏,如图:
上方的Hello所在的那一栏就是我所说的导航栏。如果用自带的这一个导航栏的话滑动时候效果如图:
此图可看出:使用滑动菜单时候不会隐藏掉系统给我们的导 航栏,所以我们不用系统给出的导航栏,将最上方提到的代码替换为:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
然后我们新建自己的“导航栏”(用ToolBar来替换原来的):
首先在布局文件中activity_main.xml中写以下的代码:
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/toolbar"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/Theme.AppCompat.Light"/>
</FrameLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:text="This is a text"
android:textSize="30sp"
android:background="#FFF"/>
</androidx.drawerlayout.widget.DrawerLayout>
然后在对应的MainActivity中写下下面的几句话:
public class MainActivity extends AppCompatActivity {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.setting:
Toast.makeText(MainActivity.this , "You clicked setting" , Toast.LENGTH_LONG).show();
break;
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar , menu);
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
}
}
注意此处导入的为ToolBar为:
import androidx.appcompat.widget.Toolbar;
运行效果如下:
现在我们发现呼出侧滑时候上方的导航栏也隐藏在后面,就很nice。
但是现在界面还很难看,不过不着急,我们进行一下优化(待写):