Android MVC Part3 The View
##什么是视图? 在 Android 中很多同学说 View 就是视图。但是 View 只有显示的能力,它不能处理响应和发送消息。先来看看视图的特点: 绑定模型 发送信息给控制器 处理控制器返回的信息 看来 activity 符合我们的要求,它可以绑定,可以处理信息,而且控制着 android 中所谓的 view 。但是 activity 又有一些其他的特性使它不像是 MVC 中的 V ,例如它管理着生命周期,而且它有一些像控制器的方法 boolean dispatchKeyEvent(KeyEvent event); boolean onOptionsItemSelected(MenuItem item); void onCreateContextMenu(….); so on…. 要知道 dispatchEvent 如果返回 true 表示这个 activity 会处理该事件。但是实际上,处理事件的逻辑应该交给控制器做的。 我们通过一些方法来避免上述的问题,使 activities 更像是一个视图。其灵感来源于这篇文章 为了把 activity 变成 view ,我们做了下面的操作。 ##1. 数据绑定 来看看 TapActivity 是如何绑定数据的 :::java package com.lingavin.tapcounter.activities; import com.lingavin.tapcounter.R; import com.lingavin.tapcounter.R.layout; import com.lingavin.tapcounter.vos.CounterVo; import com.lingavin.tapcounter.vos.OnChangeListener; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; public class TapActivity extends Activity implements OnChangeListener { private static final String TAG = TapActivity.class.getSimpleName(); private CounterVo mCounterVo; private EditText label; private TextView count; private Button minusBtn; private Button plusBtn; private CompoundButton lockedBtn; private static final int UPDATE_VIEW = 0; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); int what = msg.what; switch(what){ case UPDATE_VIEW: updateView(); break; default: } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mCounterVo = new CounterVo(); mCounterVo.addListener(this); initViews(); } private void initViews() { lockedBtn = (CompoundButton) findViewById(R.id.lockBtn); ...... } @Override public void onChange(Object model) { mHandler.sendEmptyMessage(UPDATE_VIEW); } private void updateView(){ if(!label.getText().toString().equals(mCounterVo.getLabel())) label.setText(mCounterVo.getLabel()); label.setEnabled(!mCounterVo.isLocked()); count.setText(Integer.toString(mCounterVo.getCount())); lockedBtn.setChecked(mCounterVo.isLocked()); } } 在 onCreate 函数中我们实例化了 CounterVo 并把 TabActivity 作为观察者注册上 mCounterVo 。 ...