问题
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.
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?
partial Activity file:
...
private ViewFlipper viewflipper;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardviewinput);
viewflipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
partial xml file:
...
<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>
partial fragment file:
...
@Override
public void onClick(View v) {
...
dismiss();
getActivity().viewflipper.setDisplayedChild(viewflipper.indexOfChild
(findViewById(R.id.cardviewNobuttons)));
}
回答1:
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
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:
- Otto
- EventBus
来源:https://stackoverflow.com/questions/33967201/android-what-is-the-best-way-to-update-the-activity-view-from-within-a-fragment