gpt4 book ai didi

android - 如何从 fragment B访问 fragment A的按钮

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

我的 Activity 中有两个 Fragment:带有按钮 X 的 fragment A 和 fragment B 带有按钮 Y

如何在单击按钮 B 时更改按钮 X 的背景图像?可能吗?

最佳答案

来自文档,

Because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.

话虽这么说,你想要做的是create event callbacks to the activity .这样做的一个好方法是在 fragment 内定义一个回调接口(interface),并要求宿主 Activity 实现它。当 Activity 通过接口(interface)接收到回调时,它可以根据需要与布局中的其他 fragment 共享信息。这是在两个单独的 Fragment 之间共享事件的推荐方式,即通过 Activity 共享事件。

查看上面的链接...它提供了几个很好的示例。如果您仍然遇到问题,请告诉我,也许我可以更明确。


编辑#1:

假设您单击了 fragment A 中的一个按钮,并且您希望这会导致 fragment B 中的按钮发生变化。下面是一些说明该概念的示例代码:

回调接口(interface):

public interface OnButtonClickedListener {
public void onButtonClicked();
}

Activity :

public class SampleActivity extends Activity implements OnButtonClickedListener {

/* Implementation goes here */

public void onButtonClicked() {
// This method is called from fragment A, and when it is called,
// it will send information to fragment B. Remember to first
// check to see if fragment B is non-null.

/* Make call to a method in fragment B that will update its display */
}
}

fragment A:

public class FragmentA extends Fragment {
OnButtonClickedListener mListener;

/* Implementation goes here */

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnButtonClickedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonClickedListener ");
}
}

public void clickButton() {
// When the button is clicked, notify the activity.
// The activity will then pass the information to fragment
// B (if it has been created).

mListener.onButtonClicked();
}
}

编辑#2:

现在,您可能想知道,“为什么会有人经历所有这些麻烦?当您可以让 fragment A 直接操作 fragment 时,创建一个单独的 Activity 回调方法有什么意义 B?”

您要这样做的主要原因是确保每个 fragment 都设计为模块化和可重用的 Activity 组件。这一点尤其重要,因为模块化 fragment 允许您针对不同的屏幕尺寸更改 fragment 组合。在设计支持平板电脑和手机的应用程序时,您可以在不同的布局配置中重复使用您的 fragment ,以根据可用的屏幕空间优化用户体验。例如,在手机上,当同一 Activity 无法容纳多个 fragment 时,可能需要分离 fragment 以提供单 Pane UI。使用 Activity 回调可确保在屏幕上看不到 fragment B 的情况下,您可以轻松地重用 fragment 。例如,如果您在手持设备上并且没有足够的空间来显示 fragment B,那么您可以轻松地检查您的 Activity 以查看 fragment B 当前是否显示在屏幕上。

抱歉,如果不清楚...我发现很难描述 :P。努力解决这个问题 tutorial可能会有所帮助...作为开发人员,当您使用交互式多 Pane 布局时, Activity 回调让您的生活变得特别轻松。

关于android - 如何从 fragment B访问 fragment A的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10695473/

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