Android:从片段中更新“活动"视图的最佳方法是什么? [英] Android: what is the best way to update the Activity view from within a fragment?

查看:81
本文介绍了Android:从片段中更新“活动"视图的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DialogFragment ,当用户在对话框上单击确定"时,将其关闭,我想重新绘制活动布局.

I have a DialogFragment and when the user clicks "Ok" on the dialog it is dismissed and I want to re-draw the activity layout.

我正在为 Activity 中的三种布局使用 viewflipper .我是否在片段内使用 getActivity()来访问 viewflipper ,以便可以更新布局视图?

I am using a viewflipper for three layouts within the Activity. Do I use getActivity() within the fragment to access the viewflipper so that the layout view can be updated?

部分活动文件:

...
private ViewFlipper viewflipper;

protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cardviewinput);
    viewflipper = (ViewFlipper) findViewById(R.id.viewFlipper1);

部分xml文件:

...
<LinearLayout
    android:id="@+id/LinearLayout3"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center_vertical"  >

<ViewFlipper
    android:id="@+id/viewFlipper1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<include layout="@layout/cardview_nobuttons"
    android:id="@+id/cardviewNobuttons"  />

<include layout="@layout/cardview_previewbuttons"
    android:id="@+id/cardviewPreviewbuttons" />

<include layout="@layout/cardview_twobuttons"
    android:id="@+id/cardviewTwobuttons"  />

</ViewFlipper>

</LinearLayout>  

部分片段文件:

...
@Override
public void onClick(View v) { 
...   
dismiss();
getActivity().viewflipper.setDisplayedChild(viewflipper.indexOfChild
   (findViewById(R.id.cardviewNobuttons)));
}

推荐答案

我强烈建议您反对这种方法.片段不应与其托管活动直接通信.与活动"进行通讯a>

I would strongly recommend you against this approach. Fragments shouldn't directly communicate with their hosting Activity. There is an official guide talking exactly about how to approach this issue Communicating with the Activity

此外,我建议您看一下EventBus模式,它可以使这种通信更加容易.有两种专门针对Android的流行实现:

Also, I suggest you to take a look at EventBus pattern, which could make this communication much easier. There are two popular implementations specifically for Android:

这篇关于Android:从片段中更新“活动"视图的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆