DrawerLayout布局的使用步骤
作者:互联网
说明:
DrawerLayout:内部有两个子布局(或者控件)
ScrollView中只能有个布局。先写的是内容(主布局),后写的是侧滑布局( android:layout_gravity="left")
acvitity_main.xml
<android.support.v7.widget.Toolbar
android:id="@+id/tb_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"/>
<android.support.v4.widget.DrawerLayout
android:id="@+id/dl_layout"
android:background="@android:color/holo_orange_light"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--先定义主布局内容 -->
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="内容"
android:textSize="25sp"/>
<!--后定义侧滑的布局 -->
<ListView
android:id="@+id/lv_menu"
android:layout_width="220dp"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:layout_gravity="left" >
</ListView>
</android.support.v4.widget.DrawerLayout>
MainAcvitity.java
public class MainActivity extends AppCompatActivity {
private Toolbar tb_bar;
private TextView tv_content;
private ListView lv;
private DrawerLayout dl_layout;
private String[] menus = new String[]{"item1", "item2", "item3", "item4", "item5", "item6"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiView();
}
public void intiView(){
tb_bar= (Toolbar) findViewById(R.id.tb_bar);
tv_content= (TextView) findViewById(R.id.tv_content);
lv= (ListView) findViewById(R.id.lv_menu);
dl_layout= (DrawerLayout) findViewById(R.id.dl_layout);
//给listview设置展示的数据
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,menus);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
tv_content.setText(menus[position]);
if(dl_layout.isDrawerOpen(Gravity.LEFT)){//如果此时抽屉窗口打开,就给他关闭
dl_layout.closeDrawer(Gravity.LEFT);
}
}
});
//给Toolbar设置左上角的图标和监听事件
tb_bar.setNavigationIcon(R.drawable.ic_drawer_home);
tb_bar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//如果抽屉关闭就打开,如果抽屉打开就关闭
if(dl_layout.isDrawerOpen(Gravity.LEFT)){
dl_layout.closeDrawer(Gravity.LEFT);
}else {//如果已经是关闭状态
dl_layout.openDrawer(Gravity.LEFT);
}
}
});
标签:bar,dl,layout,步骤,布局,Gravity,lv,DrawerLayout,tb 来源: https://blog.51cto.com/u_15249199/2847168