gpt4 book ai didi

java - Android 选项卡式 Activity - 将微调器值从嵌套 fragment 传递到父 Activity 中的选项卡 fragment

转载 作者:太空宇宙 更新时间:2023-11-04 14:00:21 26 4
gpt4 key购买 nike

这真是拗口。我有一个带有两个选项卡的基本选项卡式 Activity ,每个选项卡与微调器共享一个 fragment ,该 fragment 在每个选项卡的布局文件中声明:

选项卡 1:

<fragment android:name="com.me.fragment.DetailsFragment"
android:id="@+id/DetailsFragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

选项卡 2:

<fragment android:name="com.me.fragment.DetailsFragment"
android:id="@+id/DetailsFragment2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

主 Tabbed Activity 类当然有两个嵌套的静态 Fragment 类;每个选项卡一个。

public class MyTabbedActivity extends FragmentActivity
{
public static class FirstTabFragment extends Fragment
{
//get value from DetailsFragment and "refresh" display values
}

public static class SecondTabFragment extends Fragment
{
//...
}
}

我试图将上面嵌套的DetailsFragment中微调器的选定值传递给选项卡式 Activity 中的嵌套静态选项卡类,以便可以在其中过滤数据。

也就是说...首次加载 Activity 时,将调用一组默认数据并将其显示在选项卡中。当DetailsFragment中的微调器选择发生变化时,参数会传递到选项卡类,并且数据会被过滤,显示的值也会发生变化。

我可以通过接口(interface)将 a 值从 DetailsFragment 传递到主 Activity (MyTabbedActivity),但不确定如何将该值传递到嵌套的 FirstTabFragment 和 SecondTabFragment fragment ,并刷新/重新加载 View 。

最好的方法是什么?

最佳答案

如果您愿意使用库,我强烈推荐 Event Bus .

然后在您的详细信息 fragment 中您只需执行

EventBus.getDefault().post(value);

并在您想要接收增值的 fragment 中

EventBus.getDefault().register(this);

到 onCreate 并创建一个名为的方法

public void onEvent(ValueType value){
// do what you want with the value here
}

这将获取您的值并将其发布到与该值类型匹配的任何内容(即,如果您的值是字符串,则任何采用字符串作为参数的 onEvent 方法都将接收该值)。因此,建议创建一个事件类来传递。

public class DetailFragmentEvent{
private String value;

public DetailFragmentEvent(String value){
this.value = value;
}

public String getValue(){
return value
}
}

然后将其传递到您的帖子中。这样您就可以将事件分开。您可以将事件总线与几乎任何您想要的对象一起使用,并且它比编写大量接口(interface)简单得多。

此外,在任何注册事件总线的类中,在销毁时取消注册它。

@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}

关于java - Android 选项卡式 Activity - 将微调器值从嵌套 fragment 传递到父 Activity 中的选项卡 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29352920/

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