简体   繁体   English

Android - 如何从活动中包含的片段更新活动视图

[英]Android - how to update activity view from fragment contained in the activity

Concise : I am looking for a way to update a view in an activity from a fragment that the activity contains.简洁:我正在寻找一种方法来从活动包含的片段更新活动中的视图。

In detail : I have a fragment and an activity that contains the fragment.详细说明:我有一个片段和一个包含该片段的活动。 The activity has a navigation drawer and the navigation drawer contains a image view.该活动有一个导航抽屉,导航抽屉包含一个图像视图。 What I am trying is to update the image view in the navigation drawer when a HTTP GET request returns a response from the fragment;我正在尝试的是当 HTTP GET 请求从片段返回响应时更新导航抽屉中的图像视图; the response contains a URL to where an image loader parses an image for the image view in the navigation drawer.响应包含一个 URL,指向图像加载器为导航抽屉中的图像视图解析图像的位置。

Given this, I am trying to get an instance of the view in the activity from the fragment, but I am not sure how to do so.鉴于此,我试图从片段中获取活动中的视图实例,但我不确定如何执行此操作。 Even, I am not sure if I am on the right direction...甚至,我不确定我是否在正确的方向上......

I will greatly appreciate any input.我将不胜感激任何输入。

Regards,问候,

Create Interface:创建接口:

public interface mInterface{

  public void updateIMG(String url);

}

Implement this interface inside your activity and Override updateIMG() method.在您的活动中实现此接口并覆盖updateIMG()方法。

Inside your fragment what ever you need to call updateIMG() just initiate interface and call a method.在您的片段中,您需要调用updateIMG()只需启动接口并调用一个方法。

mInterface listener =  (mInterface)getActivity();
listener.updateIMG(url);

Then you call this interface method it will run code inside overrided method inside activity.然后你调用这个接口方法,它会在活动的重写方法中运行代码。


In case you get Only the original thread that created a view hierarchy can touch its views.如果您获得只有创建视图层次结构的原始线程可以触摸其视图。 , try . 试试

将视图声明为要更新的公共视图,然后您可以从片段访问该视图并可以从那里更新

You can use a LocalBroadCast to send a broadcast from Fragment whenever needed and then receive the broadcast in Activity and do the changes.您可以使用LocalBroadCast在需要时从Fragment发送广播,然后在Activity接收广播并进行更改。

You can also implement Activity , Fragment communication through an interface .也可以通过一个interface实现ActivityFragment通信。 Refer this link to implement the same.请参阅此链接以实现相同的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM