gpt4 book ai didi

Android - 抽屉导航 fragment

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:11 25 4
gpt4 key购买 nike

我已经在我的 android 应用程序中实现了抽屉导航。但现在我希望能够在用户单击导航栏中的任何列表项时使用 fragment 更改布局。这是我到目前为止所得到的:

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);
}
});
}
}

使用上面的代码,我在我的应用程序中实现了抽屉导航,我在抽屉导航中看到了“一个”、“两个”和“三个”列表项,但是当我点击它们时除了抽屉关闭之外没有任何反应。所以,我的问题是:如何将 fragment 功能添加到上面给定的代码中?

我是初学者。提前致谢!

最佳答案

点击有

  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 - 抽屉导航 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21059179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com