在Fragment中使用Observer

时间:2013-02-15 13:21:59

标签: android fragment observer-pattern observable

我在片段中使用观察者时遇到问题,我已经实现了自己的TextViewObserver,我不想将它插入片段中:

public class TextViewObserver extends TextView implements Observer {

public TextViewObserver(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public TextViewObserver(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public TextViewObserver(Context context) {
    super(context);
}

@Override
public void update(java.util.Observable o, Object arg) {
    // TODO Auto-generated method stub
    this.setText(String.valueOf(arg));

}

我的片段代码:

public class MyFragment extends Fragment {
private TextViewObserver mTextView;// = new TextView(this.getActivity());
private ApplicationContext mContext;
private DataObservable mDataObservable;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_6, container, false);
    mTextView = (TextViewObserver) view.findViewById(R.id.sicthtxtview);
    return view;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mContext = (ApplicationContext) activity.getApplicationContext();
    mDataObservable = mContext.getObservable();

}

@Override
public void onStart() {
    super.onStart();
    mDataObservable.addObserver(mTextView);
}

我的DataObservable在我的类ApplicationContext(扩展Application)中:

public class ApplicationContext extends Application {

private DataObservable _mData;

@Override
public void onCreate() {
    super.onCreate();
    _mData = new DataObservable();
}

public DataObservable getObservable() {
    return _mData;
}

当DataObservable更改时,必须通知MyTextViewObserver,并在Fragment中的结果setText中通知。 这是LogCat给出的错误:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

THX

1 个答案:

答案 0 :(得分:3)

在Android中,您只能从UI线程中操纵View。您可以使用View.post()在UI线程上运行一些代码,如下所示:

@Override
public void update(java.util.Observable o, final Object arg) {
    this.post(new Runnable() {
        public void run() {
            this.setText(String.valueOf(arg));
        } 
    }
}

http://developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)