如何将导航抽屉与其他组件一起使用?
我的activity_main是
<LinearLayout
android:id="@+id/ListView"
android:layout_width="match_parent"
android:layout_height="262dp"
android:orientation="vertical" >
<Button
android:id="@+id/button0"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="@drawable/..."
/>
...
</LinearLayout>
使用这个xml文件,我想在我的App中添加导航抽屉。
答案 0 :(得分:0)
activity_main.xml
:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<LinearLayout
android:id="@+id/ListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- your buttons and whatever else is in your main layout -->
</LinearLayout>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
要初始化抽屉,请MainActivity.java
:
public class MainActivity extends Activity
{
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
...
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close)
{
public void onDrawerClosed(View view)
{
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(yourAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{
// Deal with the selection
selectItem(position);
}
});
}
}
要处理导航栏的点击事件,请参阅here。
要收听导航抽屉的打开和关闭事件,请参阅here。