Android的 - 导航抽屉片段 [英] Android - Navigation drawer fragments
问题描述
我已经在我的Android应用程序来实现导航的抽屉里。但现在我希望能够使用的片段,当用户点击导航栏中的任何列表项改变布局。 以下是我有这么远:
I have implemented navigation drawer in my android app. but now I want to be able to change the layout using fragments when the user clicks any list item in the navigation bar. Here is what I have got so far:
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<ListView android:id="@+id/left_drawer"
android:layout_width="220dp"
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>
Java文件
public class MainActivity extends Activity {
final String[] data ={"one","two","three"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
@Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
}
});
drawer.closeDrawer(navList);
}
});
}
}
使用上述code,我实现了抽屉式导航在我的应用程序,我见一,二和三列表项中的抽屉式导航,但没有任何反应,当我点击他们除了抽屉关闭。 所以,我的问题是: 如何添加片段功能上面给出code?
Using the above code, I implemented navigation drawer in my app and I see "one", "two" and "Three" list items in the navigation drawer but nothing happens when I click on them except the drawer closes. So, my question is : How do I add the fragment functionality to the above given code?
我是初学者。在此先感谢!
I am beginner. Thanks in advance!
推荐答案
在点击有
selectItem(pos);
然后
public void selectItem(int position)
{
switch(position)
{
case 0:
// fragment1
// use fragment transaction and add the fragment to the container
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment = new Fragment1();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.commit();
break;
case 1:
// fragment2
break;
case 2:
// fragment2
break;
}
}
这篇关于Android的 - 导航抽屉片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!