类似于适配器的模式,而不是AdapterView类

时间:2014-02-02 14:34:07

标签: android architecture

我需要将数据从我的活动层传输到一个不属于AdapterView的视图(或至少它的片段)。
对于ListView,我可以使用其适配器轻松完成此操作,但我仍然坚持如何为非AdapterView小部件重现此行为(为清楚起见,假设是一个TextView)。 我不想在活动级别保留对我的片段(或更糟糕的是,视图)的引用 有什么想法吗?

1 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是使用java.util.Observable / Observer:

import java.util.Observable;
import java.util.Observer;


public class MyTextView extends View implements Observer{



    @Override
    public void update(Observable observable, Object data) {
        this.setText((String)data);
    }

}

然后,你需要一个Observable类:

import java.util.Observable;

public class MyObservable extends Observable {


    public void setText(String text){

            notifyObservers(text);
    }

}

活动:

public class MainActivity extends Activity {
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    MyObservable mtv = new MyTextView(getApplicationContext());
    MyTextViewModel mm = new MyTextViewModel(10);
    mm.addObserver(mtv);
    mm.setText("test");
    // demonstrated in an activity to shorten the sample, but ideally you would
    // keep the observer at activity level and manage the view in the fragment
    }
}

----------------------------------------------- -

另一种方法是通过android.database.DataSetObservable来实现更像传统的适配器对象:

public class CustomAdapter extends DataSetObservable {
   String mText;

   public String getText() {
      return mText;
   }

   public void setText(String text) {
      mText = text;
   }
}

您可以像活动级别的任何其他适配器一样操纵它:
公共类MyActivity扩展Activity { 私人CustomAdapter mCustomAdapter;

@覆盖     protected void onCreate(){     ...     mCustomAdapter = new CustomAdapter();     }

private void initializeFragment (Fragment fragment) {
// this or whatever method you use to setup your fragments
((MyFragment) fragment).setCustomAdapter(mCustomAdapter);
}

private void onDataLoaded (Stg data) {
// callback method invoked when the network thread has finished loading data
mCustomAdapter.setText(data.text);
mCustomAdapter.notifyChanged();
}

最后,唯一缺少的是片段和视图之间的链接:

public class MyFragment extends Fragment {
private CustomAdapter mCustomAdapter;  

public setCustomAdapter(CustomAdapter adapter) {
    // this method allows to setup the adapter at startup
    mCustomAdapter = adapter;
}

protected DataSetObserver mMyViewObserver = new MyObserver();

private class MyObserver extends DataSetObserver {

    @Override
    public void onChanged() {
     mUpdateHandler.sendEmptyMessage(0);
     }
}

private Handler mUpdateHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        updateMyView();
        }
    };

    private void updateMyView() {
       if (mView == null) {
           return;
       }
       mView.setMainTextViewText(mCustomAdapter.getText());
    }

}

在这里你拥有它。每次调用notifyChanged()时,都会调用您的观察者。作为回报,他调用更新视图的处理程序。 在这里,您可以使用任何类型的视图,无泄漏,线程安全的自定义适配器。