如何从其他Activity更改一个Activity的ListView中的数据

时间:2013-05-11 11:25:35

标签: android listview

我在SOF上看到的问题很少,但他们都没有帮助。

在我的应用程序中,我有一个用户列表,可以通过单击用户的朋友来访问。流程是:

  
      
  1. 转到我的个人资料

  2.   
  3. 点击我的朋友转到包含用户列表的活动(我的朋友)

  4.   
  5. 点击任何listView项目对该用户的个人资料

  6.   
  7. 从该个人资料中我可以看到用户的朋友列表与我的相同。

  8.   

问题是所有这些listView项目都有add as friend的按钮,这使得我和该用户成为该列表中的朋友(比如跟随Twitter中的关注更改)现在我通过backstack返回,并在某处用户所在的listView之一,按钮仍然是add as friend

如何在所有ListView中更改该用户的按钮(我的适配器数据中的标志)?

1 个答案:

答案 0 :(得分:1)

使用Interface将事件发送回活动,并在收到活动时更新列表或数据库。

接口是将消息传递给“外部世界”的方式。只需看一个简单的button onClickListener。您基本上会在按钮上调用setOnClickListener(this),并在此处实施onClickListener interface。只要单击该按钮,您就会在onClick中收到一个事件。这是在不需要意图的活动之间传递消息的最安全的方法(根据我的说法,这是一个巨大的痛苦......)这是一个例子:

示例:

class A extends Activity implements EventInterface{

    public A(){

        //set a listener. (Do not forget it!!!)
        //You can call it wherever you want; 
        //just make sure that it is called before you need something out of it.
        //safest place is onCreate.
        setEventInterfaceListener( A.this );

    }      

    //this method will be automatically added once you implement EventInterface.
    void eventFromClassB(int event){

         //you receive events here.
         //Check the "event" variable to see which event it is.

    }         

}


class B{

    //Interface logic
    public interface EventInterface{
        public static int BUTTON_CLICKED = 1;

        void eventFromClassB(int event);
    }
    static EventInterface events;

    public static void setEventInterfaceListener(EventInterface listener) {
        events = listener;
    }

    private void dispatchEvent(int trigger) {
        if (events != null) {
            events.eventFromClassB(trigger);
        }
    }

    //Interface ends

    void yourMethod(){

       //Call this whenever you want to send an event.
       dispatchEvent( BUTTON_CLICKED );

    }

}
相关问题