我正在实现Android Java应用程序,其中有两种类型的用户。他们中的每一个都有权限使用一些应用程序功能,但不是所有功能。
我目前的实现包括每次用户被重定向到同一个活动时,在该活动中设置所有组件的可见性。示例:
protected void onCreate(Bundle savedInstanceState) {
if(!userLoggedIn()) {
// Set all visibilities
} else if (loggedUserType() == UserType.USER1) {
// Set all visibilities
} else {
// Set all visibilities
}
}在android java应用程序中有没有标准的方法来说明如何处理这个问题?如果没有,有没有比上面的例子更好的方法呢?
发布于 2020-02-03 00:02:50
您可以为每个用户类型创建一个fragment,并在您的活动中显示该片段。在您的活动布局中添加一个容器。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
//rest of activty views
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>并根据用户类型创建并添加您的片段
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment;
if(!userLoggedIn()) {
fragment = new ExampleFragment1();
} else if (loggedUserType() == UserType.USER1) {
fragment = new ExampleFragment2();
} else {
fragment = new ExampleFragment3 ();
}
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();通过这种方式,您将拥有干净的体系结构,并且可以单独更改每个片段
https://stackoverflow.com/questions/60026769
复制相似问题