Use Observer in Fragment

五迷三道 提交于 2019-12-12 16:09:48

问题


I've a problem when using an observer in a fragment, I've implemented my own TextViewObserver, and I wan't to insert it in a Fragment:

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));

}

My fragment code:

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);
}

My DataObservable is in my class ApplicationContext (extending Application):

public class ApplicationContext extends Application {

private DataObservable _mData;

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

public DataObservable getObservable() {
    return _mData;
}

MyTextViewObserver have to be notified when the DataObservable change, and in result setText in the Fragment. This is the error given by the LogCat:

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

Thx


回答1:


In Android, you can only manipulate Views from the UI thread. You can run some code on the UI thread by using View.post(), like this:

@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)



来源:https://stackoverflow.com/questions/14895729/use-observer-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!