我是Android开发的初学者,我想创建一个带有导航抽屉的应用程序。 我从Android Studio的“创建项目”窗口中的默认模板开始。
这是MainActivity中的代码,用于设置抽屉导航。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_customers, R.id.nav_notes, R.id.nav_stats, R.id.nav_settings)
.setDrawerLayout(drawer)
.build();
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
我有一个片段是“客户”页面。 此页面包含一个按钮,用户可以单击该按钮创建新客户。 当单击该按钮时,应该打开一个新页面,该页面接受创建客户的输入。 这个新页面不应该是用户可以直接导航到的导航项。 打开该页面的唯一方法和理由应该是使用我提到的customers视图中的“Create Customer”按钮。
因此,该新页面不应包含在导航抽屉的菜单中。 同时,我确实想给这个页面自己的工具栏。
最重要的两件事似乎是:
看起来很简单,我也试了很多,但到目前为止我还没有找到任何解决方案。
您可以查看文档:
在图中定义如下内容:
<fragment android:id="@+id/a"
android:name="com.example.myapplication.FragmentA"
android:label="a"
tools:layout="@layout/a">
<action android:id="@+id/action_a_to_b"
app:destination="@id/b"/>
</fragment>
<fragment android:id="@+id/b"
android:name="com.example.myapplication.FragmentB"
android:label="b"
tools:layout="@layout/b">
</fragment>
然后只需使用导航:
findNavController().navigate(R.id.action_a_to_b)
请同时检查此页:
当应用程序中每个目的地的应用程序栏布局相似时,将顶部应用程序栏添加到您的activity中效果很好。 但是,如果您的顶部应用程序栏在不同的目的地之间发生了实质性的变化,那么可以考虑将顶部应用程序栏从您的activity中删除,并在每个目的地片段中定义它。
在OnCreateView
中的片段B
中,可以膨胀布局
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_B container, false)
在此布局中,您可以放置工具栏
:
<LinearLayout>
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
... />
...
</LinearLayout>
和:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navController = findNavController()
val appBarConfiguration = AppBarConfiguration(navController.graph)
view.findViewById<Toolbar>(R.id.toolbar)
.setupWithNavController(navController, appBarConfiguration)
}
另一种方法是在activity中设置导航并使用OnDestinationChangedListener
:
navController.addOnDestinationChangedListener { _, destination, _ ->
if(destination.id == R.id.b) {
toolbar.visibility = View.GONE
//....
} else {
toolbar.visibility = View.VISIBLE
//.....
}