MVC for Android

一个简单的MVC pattern for android:


MVC for Android_第1张图片
MVC for Android_第2张图片

MVCActivity为控制器,点击event按钮,触发model改变,回调MVCActivity update接口,更新View

packagecom.sanyinchen.mvcdemo;

importandroid.support.v7.app.ActionBarActivity;

importandroid.os.Bundle;

importandroid.util.Log;

importandroid.view.Menu;

importandroid.view.MenuItem;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.TextView;

importjava.util.Observable;

importjava.util.Observer;

public classMVCActivityextendsActionBarActivityimplementsObserver,View.OnClickListener {

privateTextViewt1;

privateTextViewt2;

privateTextViewt3;

privateButtonb1;

privateButtonb2;

privateButtonb3;

privateModelmodel;

@Override

protected voidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_mvc);

t1= (TextView) findViewById(R.id.model1);

t2= (TextView) findViewById(R.id.model2);

t3= (TextView) findViewById(R.id.model3);

b1= (Button) findViewById(R.id.event1);

b2= (Button) findViewById(R.id.event2);

b3= (Button) findViewById(R.id.event3);

b1.setOnClickListener(this);

b2.setOnClickListener(this);

b3.setOnClickListener(this);

model=newModel();

model.addObserver(this);

}

@Override

public voidupdate(Observable observable,Object data) {

Log.i("TAG","get value");

t1.setText("value: "+model.getValueOfIndex(0));

t2.setText("value: "+model.getValueOfIndex(1));

t3.setText("value: "+model.getValueOfIndex(2));

}

@Override

public voidonClick(View v) {

switch(v.getId()) {

caseR.id.event1:

model.setValueOfIndex(0,model.getValueOfIndex(0) +1);

break;

caseR.id.event2:

model.setValueOfIndex(1,model.getValueOfIndex(1) +1);

break;

caseR.id.event3:

model.setValueOfIndex(2,model.getValueOfIndex(2) +1);

break;

}

}

}

Model:

packagecom.sanyinchen.mvcdemo;

importandroid.util.Log;

importjava.util.ArrayList;

importjava.util.List;

importjava.util.Observable;

/**

* Created by sanyinchen on 15/4/18.

*/

public classModelextendsObservable {

ListmList=null;

publicModel() {

mList=newArrayList(3);

mList.add(0);

mList.add(0);

mList.add(0);

}

public intgetValueOfIndex(final intthe_index) {

returnmList.get(the_index);

}

public voidsetValueOfIndex(intthe_index, intthe_value) {

Log.i("TAG","the value is "+ the_value);

mList.set(the_index,the_value);

setChanged();

notifyObservers();

}

}

Model继承自Observable,MVCActivity 调用setValueofIndex(int ~)更新model,同时setChanged(),使用notifyObservers()通知所有注册该model的controller,即model.addobserver(this)这句为注册

Github:https://github.com/sanyinchen/MVCDemo

你可能感兴趣的:(MVC for Android)