gpt4 book ai didi

java - 如何使用多态性在运行时根据实例加载 fragment ?

转载 作者:行者123 更新时间:2023-12-01 18:40:24 25 4
gpt4 key购买 nike

我有一个选项卡布局,其中包含 3 个选项卡项,每个选项卡项都有自己的 fragment ,可以在选择时在运行时加载。

MainActivity.class:这里根据所选选项卡的位置调用LoadFragment。

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
LoadFragment(new LocationFragment());
break;
case 1:
LoadFragment(new InformationFragment());
break;
case 2:
LoadFragment(new CommentsFragment());
break;
}
}

我的问题是如何使用 switch 语句作为逻辑来使用 fragment 管理器加载正确的 fragment ?我不想有 if else 语句层次结构。

private void LoadFragment(Fragment fragment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

switch (*some logic here*) {

case fragment instanceof LocationFragment:
Log.i("MainActivity", "inside load fragment");
ft.replace(R.id.coordinate_layout, new LocationFragment());
break;


case fragment instanceof InformationFragment:
ft.replace(R.id.coordinate_layout, new InformationFragment());
break;


case fragment instanceof CommentsFragment:
ft.replace(R.id.coordinate_layout, new CommentsFragment());
break;

ft.commit();

}
}

最佳答案

您不需要多次创建实例,您只需传递类型即可,在加载时您可以决定需要加载哪个 fragment 。

    private static final int TYPE_LOCATION=0;
private static final int TYPE_INFO=1;
private static final int TYPE_COMMENT=2;

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
LoadFragment(TYPE_LOCATION);
break;
case 1:
LoadFragment(TYPE_INFO);
break;
case 2:
LoadFragment(TYPE_COMMENT);
break;
}
}

private void LoadFragment(int typeOfFragment) {
Log.i("MainActivity", "inside load fragment");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

switch (typeOfFragment) {

case TYPE_LOCATION:
ft.replace(R.id.coordinate_layout, new LocationFragment());
break;


case TYPE_INFO:
ft.replace(R.id.coordinate_layout, new InformationFragment());
break;


case TYPE_COMMENT:
ft.replace(R.id.coordinate_layout, new CommentsFragment());
break;

ft.commit();

}
}

关于java - 如何使用多态性在运行时根据实例加载 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59943149/

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