下面两段标红加深的代码是重点:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import java.util.Observable;
import java.util.Observer;

// you must implements Observer
public class ObserverExample extends Activity implements Observer { // Button variables for our 4 UI buttons which perform touchdowns and field
// goals for the Home and Away teams.
Button button1;
Button button2;
Button button3;
Button button4; // Score variable for the Score object we'll be using to track and report
// out both teams' scores.
Score score; // TextView variables for our scoreboard display, #2 is Home score, #4 is
// Vistors score.
TextView textView2;
TextView textView4; // Set some constants to make the code more human-readable.
private static final int HOME = 1;
private static final int VISITOR = 2; @Override
public void update(Observable observable, Object data) { // Set the score to the current score each time there's a change.
// Creating a helper method is a nice way to simplify the code here.
setScore();
} // Grabs the score for the Home team and Away team and displays them in
// the correct TextView's of the scoreboard. private void setScore() { textView2.setText(String.valueOf(score.getScore(HOME)));
textView4.setText(String.valueOf(score.getScore(VISITOR)));
} @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Create a new score object, this will contain all of the logic to
// track and report out both team's scores.
score = new Score(); // Score is an Observable class, therefore, we can use the method
// addObserver to add this Activity as an Observer using it's local
// context. This is the magic sauce that enables instant updates
// whenever the Score changes. When the Score reports a change, the
// update() method runs in this Activity.
score.addObserver(this); // This code ties in our TextView variables to the actual ID's of the UI
// elements themselves.
textView2 = (TextView) findViewById(R.id.textView2);
textView4 = (TextView) findViewById(R.id.textView4); // Ties in the ID of the button to our variable set above.
button1 = (Button) findViewById(R.id.button1); // Creates a new instance of OnClickListener which fires the onClick()
// method upon, well, a click.
button1.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { // Update the score by running the touchDown() method for the
// Home team.
score.touchDown(HOME); }
}); // Same idea as above repeated for buttons 2 - 4.
button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { // Update the score by running the fieldGoal() method for the
// Home team.
score.fieldGoal(HOME); }
}); button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { score.touchDown(VISITOR);
}
}); button4 = (Button) findViewById(R.id.button4); button4.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) { score.fieldGoal(VISITOR);
}
}); } }
import java.util.Observable;

// In order to report changes to any interested objects, such as Activities, we
// need to extend the Observable class. This enables other objects to register
// themselves as an Observer by using the addObserver() method.
public class Score extends Observable { // Initialize the score, scores always start at zero.
private int home_score = 0;
private int visitor_score = 0; public Score() { } // Grant 1 point to the team based on the variable fed in HOME == 1
// and VISITOR == 2;
public void fieldGoal(int team)
{ switch (team) {
case 1:
this.home_score = this.home_score + 1;
break; case 2:
this.visitor_score = this.visitor_score + 1;
break;
} triggerObservers(); } // Returns the score of the Home or Visitor teams depending on which
// variable is fed.
public int getScore(int team) { switch (team) {
case 1:
return home_score;
case 2:
return visitor_score;
} return 0;
} // Adds six points to score of the team fed in as a variable, HOME == 1 and
// VISITOR == 2
public void touchDown(int team) { switch (team) {
case 1:
this.home_score = this.home_score + 6;
break; case 2:
this.visitor_score = this.visitor_score + 6;
break;
} triggerObservers();
} // Create a method to update the Observerable's flag to true for changes and
// notify the observers to check for a change. These are also a part of the
// secret sauce that makes Observers and Observables communicate
// predictably.
private void triggerObservers() { setChanged();
notifyObservers();
}
}

Android之MVC——Model通知View去更新(实用)的更多相关文章

  1. MVC(Model(模型) View(视图) Controller(控制器))

    复习 1.      商品表 增删改查 index.php  add.php   view.php   edit.php   action.php 2.      MVC(Model(模型)  Vie ...

  2. MVC - Model - Controller - View

    一. Model 1.1 在ASP.NET MVC 中 model 负责的是所有与 "数据“  相关的的任务. 也可以把Model 看成是 ASP.NET  中三层模式的 BLL层 加 DA ...

  3. [Backbone]4. Model & View, toggle between Model and View. -- 1

    如上图所示: Server有Data都交给Models处理, 然后由Models给Views Data,让View去告诉DOM如何显示, 然后DOM显示HTML; View events update ...

  4. ASP.NET MVC轻教程 Step By Step 4——Model、View和Controller

    ASP.NET MVC中的Model(数据模型)主要包括定义数据结构.数据库读写.数据验证等等和对象处理相关的工作. 在解决方案资源管理器中找到Model文件夹,点击右键,添加一个新类,名为“Mess ...

  5. 使用WebFrom来模拟一些MVC的MODEL与View的数据交互功能

    MVC中有一点非常闪瞎人眼的功能就是,可以根据Model与View视图来直接将页面也数据模型进行绑定,那么我们在想客户端发送页面时不需要进行各种控件赋值,不需要操心怎么渲染,当客户提交表单给服务器时也 ...

  6. Spring MVC:Model、View、ModelAndView

    个人理解:View为服务器上的某个文件容器,可以为JSP,FTL等动态页面文件,甚至是媒体文件等等,单单是一个文件.Model的作用是存储动态页面属性,动态页面文件即View可以在Model中获取动态 ...

  7. What is the difference between Reactjs and Rxjs?--React is the V (View) in MVC (Model/View/Controller).

    This is really different, React is view library; and Rxjs is reactive programming library for javasc ...

  8. 2017年第1贴:EXT.JS使用MVC模式时,注意如何协调MODEL, STORE,VIEW,CONTROLLER的关系

    也调了快一天,死活找不到窍门. MODEL, STORE,VIEW的调置测试了很久,试了N种方法,不得其果. 最后,试着在APPLICATION里加入CONTROLLER, 在CONTROLLER里加 ...

  9. ASP.NET MVC之model传值view

    控制器中,我们有时会在知道用户名的情况下,再获取相关数据 例如: public ActionResult Index()        {            UserInfo Entity_Tem ...

随机推荐

  1. Ngram折扣平滑算法

    本文档翻译自srilm手册ngram-discount.7.html     NAME ngram-discount – 这里主要说明srilm中实现的平滑算法   NOTATION a_z      ...

  2. MFC+WinPcap编写一个嗅探器之七(协议)

    这一节是本系列教程的结尾了,内容也比较简单,主要是对网络协议进行分析,其实学过计算机网络的同学完全可以略过 在整个项目中需要有一个头文件存放各层协议的头部定义,我把它们放在了head.h中,这个头文件 ...

  3. C语言可变参数个数

    #include <stdio.h>#include <stdarg.h> void test(const char * format, ...); int main(void ...

  4. python中list和str互转

    1.list转str 假设有一个名为test_list的list,转换后的str名为test_str 则转换方法: test_str = "".join(test_list) 例子 ...

  5. Ionic Js二:背景层

    我们经常需要在 UI 上,例如在弹出框.加载框.其他弹出层中显示或隐藏背景层. 在组件中可以使用\(ionicBackdrop.retain()来显示背景层,使用\)ionicBackdrop.rel ...

  6. 牛客网 桂林电子科技大学第三届ACM程序设计竞赛 C.二元-K个二元组最小值和最大-优先队列+贪心(思维)

    链接:https://ac.nowcoder.com/acm/contest/558/C来源:牛客网 小猫在研究二元组. 小猫在研究最大值. 给定N个二元组(a1,b1),(a2,b2),…,(aN, ...

  7. 跑对抗样本库 CleverHans 的例子时,遇到的问题

    环境:Ubuntu+TensorFlow 首先是GPU被其他人占用了,怎么也跑不起来最简单的TensorFlow小例子. 所以先学会如何查看显卡使用情况,转去使用其他空闲显卡. Linux查看Nvid ...

  8. python获取当前系统的桌面的路径

    一,用内置的winreg(推荐) import winregdef get_desktop():    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\  ...

  9. 周末 “CTO训练营”

    今天下午去中关村参加了51cto高招 “CTO训练营”  第一期. 呃蛮有收获,聊技术发展,技术cto线路或对应发展,人事对应cto发展,投资人对应看法,51cto老总的看法. 呃,挺有意思,同样认识 ...

  10. Git版本管理工具对比(GitBash、EGit、SourceTree)

    Git管理工具对比(GitBash.EGit.SourceTree) GitBash是采用命令行的方式对版本进行管理,功能最为灵活强大,但是由于需要手动输入希望修改的文件名,所以相对繁琐. EGit是 ...