在片段中使用观察者时遇到问题,我已经实现了自己的 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.
谢谢