4

在片段中使用观察者时遇到问题,我已经实现了自己的 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(扩展应用程序)中:

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.

谢谢

4

1 回答 1

3

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

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

于 2013-02-15T13:34:23.960 回答