可观察/观察的Andr​​oid [英] Observable/Observer Android

查看:150
本文介绍了可观察/观察的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改请参阅观察员观测量实施问题 - 这似乎我重写了并不需要是方法,而不是调用setChanged();前通知();

我已经读了Observer模式保持我的用户界面是最新的,但我仍然无法看到使用它。即使在我的特定对象通知我MainActivity然后运行更新();方法我还是不能够使用宠物对象作为对象在OnCreate中创建抠更新值...我只是不能创建新的对象,因为这样的变量将是different..this是我的实施,它似乎并没有工作。

观察员/ MainActivity

 包com.grim.droidchi;

进口java.util.Observable中;
进口java.util.Observer;

进口android.app.Activity;
进口android.app.AlarmManager;
进口android.app.PendingIntent;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.Menu;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.webkit.WebSettings.LayoutAlgorithm;
进口android.webkit.WebView;
进口android.widget.Button;
进口android.widget.TextView;
进口android.widget.Toast;

公共类MainActivity扩展了活动实施观测,OnClickListener {
    私有静态最后字符串变量=VPET;
    私有静态最后弦乐APP_ preFS =VPET;
    私有静态最终诠释REQUEST_ code = 1;
    布尔的isAlive = FALSE;
    TextView的happiness_display,health_display,hunger_display,level_display;
    按钮PunchPet,UpdateHunger;
    公共静态宠=新Renamon();

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        共享preferences设置= getShared preferences(APP_ preFS
                MODE_PRIVATE);

        的WebView myWebView =(web视图)findViewById(R.id.pet_display);
        myWebView.loadUrl(文件:///android_asset/renamon.gif);
        myWebView.setInitialScale(10000);
        。myWebView.getSettings()setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);


        PunchPet =(按钮)findViewById(R.id.PunchPet);
        UpdateHunger =(按钮)findViewById(R.id.UpdateHunger);
        最后的TextView hunger_display =(TextView中)findViewById(R.id.hunger_display);
        TextView的happiness_display =(TextView中)findViewById(R.id.happiness_display);
        TextView的level_display =(TextView中)findViewById(R.id.level_display);
        TextView的health_display =(TextView中)findViewById(R.id.health_display);

        hunger_display.setText(Integer.toString(pet.getHunger()));
        health_display.setText(Integer.toString(pet.getHP()));
        level_display.setText(Integer.toString(pet.getLVL()));
        happiness_display.setText(Integer.toString(pet.getHappy()));


        意向意图=新的意图(这一点,Gameloop.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(),REQUEST_ code,意向,0);

        AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis的()+(5 * 1000),180万,pendingIntent);
        // 1800000毫秒= 30分钟

        pet.feed();
        pet.addObserver(本);

    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.activity_main,菜单);
        返回true;
    }

    @覆盖
    保护无效的onPause(){


        super.onPause();
    }

    @覆盖
    公共无效更新(可观察到0,对象数据){

        hunger_display.setText(Integer.toString(pet.getHunger()));
        health_display.setText(Integer.toString(pet.getHP()));
        level_display.setText(Integer.toString(pet.getLVL()));
        happiness_display.setText(Integer.toString(pet.getHappy()));
        Log.d(TAG,更新的FROM观察家);

    }

    @覆盖
    公共无效的onClick(视图v){
        如果(V == PunchPet){
            pet.setHP(500);
            Toast.makeText(getApplicationContext(),PUNCHPET,Toast.LENGTH_SHORT).show();
            health_display.setText(Integer.toString(pet.getHP()));
    }其他 {

    }



    }

}
 

观测/宠物

 包com.grim.droidchi;

进口java.util.Observable中;
进口java.util.Observer;
进口java.util.Set中;

进口android.util.Log;

公共类宠物扩展观测工具PetInterface {
    保护设置:其中,观察者GT;观察员;
    私有静态最后字符串变量=VPET;
    私人诠释健康= 100;
    @覆盖
    公共无效的addObserver(观察员O){
        observers.add(O);
        super.addObserver(O);
    }

    @覆盖
    公共无效notifyObservers(){
        observers.notify();
        super.notifyObservers();
    }

    @覆盖
    市民同步无效deleteObserver(观察员O){
        observers.remove(O);
        super.deleteObserver(O);
    }

    私人诠释幸福= 10;
    私人诠释等级= 1;
    私人诠释饥饿= 0;
    私人诠释精通= 0;
    私人字符串名称;
    私人布尔的isAlive =真;
    私人布尔isSick = FALSE;

    公共无效setHP(INT马力){
        this.Health =马力;
        notifyObservers(马力);
    }

    公共无效setLVL(INT LVL){
        this.Level = LVL;
        notifyObservers(LVL);
    }

    公共无效setXP(INT XP){
        this.Exp = XP;
        notifyObservers(XP);
    }

    公共无效setHunger(INT饥饿){
        this.Hunger =饥饿;
        notifyObservers(饥饿);
    }

    公共无效setHappy(INT高兴){
        this.Happiness =幸福;
        notifyObservers(幸福);
    }

    公众诠释getHP(){

        回到健康;
    }

    公众诠释getLVL(){

        回报水平;
    }

    公众诠释getXP(){

        返回精通;
    }

    公众诠释getHunger(){

        返回饥饿;
    }

    公众诠释getHappy(){

        回到幸福;
    }

    公共布尔的isAlive(){
        返回的isAlive;

    }

    公共布尔isSick(){
        返回isSick;

    }

    @覆盖
    公共无效睡眠(){
        // TODO自动生成方法存根

    }

    @覆盖
    公共无效清洁(){
        // TODO自动生成方法存根

    }

    @覆盖
    公共无效饲料(){
        Log.d(TAG,喂食从接口的事);

    }

    @覆盖
    公共无效passtime(){

    }

}
 

解决方案

首先,我不建议覆盖的addObserver removeObserver 在你观察的对象。该API确实实现这一点做得非常好(除非你想一些特定的功能)。

二,方法 notifyObservers()被重载,这样你可以通过它的对象,即 notifyObservers(obj对象)。如果你传递你的宠物 notifyObservers(本),那么你将有一个参考的宠物对象正在被观察到。

我觉得这是你的问题,但请纠正我,如果我错了。

修改:为了澄清,使用我的回答是当你偶然观测类的Java API中的此处

经进一步审查,你应该已经有一个参照宠物对象叫做更新方法观察

EDIT please see Observer Observables implementing issue - It seems I was overriding methods that didn't need to be and not calling setChanged(); before notify();

I've been reading up on the Observer Pattern for keeping my UI up to date but I still can't see the use for it.. Even if in my particular object notifies my MainActivity then runs the update(); method I still wouldn't be able to use the Pet object to pull the update values as the object is created in Oncreate...and I just can't create a new object because then the variables will be different..this is my implementation and it doesn't seem to work.

Observer/MainActivity

package com.grim.droidchi;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements Observer, OnClickListener {
    private static final String TAG = "VPET";
    private static final String APP_PREFS = "VPET";
    private static final int REQUEST_CODE = 1;
    Boolean isAlive = false;
    TextView happiness_display, health_display, hunger_display, level_display;
    Button PunchPet, UpdateHunger;
    public static Pet pet = new Renamon();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences settings = getSharedPreferences("APP_PREFS",
                MODE_PRIVATE);

        WebView myWebView = (WebView) findViewById(R.id.pet_display);
        myWebView.loadUrl("file:///android_asset/renamon.gif");
        myWebView.setInitialScale(10000);
        myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);


        PunchPet = (Button) findViewById(R.id.PunchPet);
        UpdateHunger = (Button) findViewById(R.id.UpdateHunger);
        final TextView hunger_display = (TextView) findViewById(R.id.hunger_display);
        TextView happiness_display = (TextView) findViewById(R.id.happiness_display);
        TextView level_display = (TextView) findViewById(R.id.level_display);
        TextView health_display = (TextView) findViewById(R.id.health_display);

        hunger_display.setText(Integer.toString(pet.getHunger()));
        health_display.setText(Integer.toString(pet.getHP()));
        level_display.setText(Integer.toString(pet.getLVL()));
        happiness_display.setText(Integer.toString(pet.getHappy()));


        Intent intent = new Intent(this, Gameloop.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), REQUEST_CODE, intent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + (5 * 1000), 1800000, pendingIntent);
        // 1800000 ms = 30 mins

        pet.feed();
        pet.addObserver(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected void onPause() {


        super.onPause();
    }

    @Override
    public void update(Observable o, Object data) {

        hunger_display.setText(Integer.toString(pet.getHunger()));
        health_display.setText(Integer.toString(pet.getHP()));
        level_display.setText(Integer.toString(pet.getLVL()));
        happiness_display.setText(Integer.toString(pet.getHappy()));
        Log.d(TAG, "UPDATED FROM OBSERVER");

    }

    @Override
    public void onClick(View v) {
        if (v == PunchPet) {
            pet.setHP(500);
            Toast.makeText(getApplicationContext(), "PUNCHPET", Toast.LENGTH_SHORT).show();
            health_display.setText(Integer.toString(pet.getHP()));
    }else {

    }



    }

}

Observable/Pet

package com.grim.droidchi;

import java.util.Observable;
import java.util.Observer;
import java.util.Set;

import android.util.Log;

public class Pet extends Observable implements PetInterface {
    protected Set<Observer> observers;
    private static final String TAG = "VPET";
    private int Health = 100;
    @Override
    public void addObserver(Observer o) {
        observers.add(o); 
        super.addObserver(o);
    }

    @Override
    public void notifyObservers() {
        observers.notify();
        super.notifyObservers();
    }

    @Override
    public synchronized void deleteObserver(Observer o) {
        observers.remove(o);
        super.deleteObserver(o);
    }

    private int Happiness = 10;
    private int Level = 1;
    private int Hunger = 0;
    private int Exp = 0;
    private String Name;
    private Boolean isAlive = true;
    private Boolean isSick = false;

    public void setHP(int hp) {
        this.Health = hp;
        notifyObservers(hp);
    }

    public void setLVL(int lvl) {
        this.Level = lvl;
        notifyObservers(lvl);
    }

    public void setXP(int xp) {
        this.Exp = xp;
        notifyObservers(xp);
    }

    public void setHunger(int hunger) {
        this.Hunger = hunger;
        notifyObservers(hunger);
    }

    public void setHappy(int happy) {
        this.Happiness = happy;
        notifyObservers(happy);
    }

    public int getHP() {

        return Health;
    }

    public int getLVL() {

        return Level;
    }

    public int getXP() {

        return Exp;
    }

    public int getHunger() {

        return Hunger;
    }

    public int getHappy() {

        return Happiness;
    }

    public boolean isAlive() {
        return isAlive;

    }

    public boolean isSick() {
        return isSick;

    }

    @Override
    public void sleep() {
        // TODO Auto-generated method stub

    }

    @Override
    public void clean() {
        // TODO Auto-generated method stub

    }

    @Override
    public void feed() {
        Log.d(TAG, "FEEDING FROM INTERFACE THING");

    }

    @Override
    public void passtime() {

    }

}

解决方案

First, I wouldn't recommend overriding addObserver or removeObserver in your observable object. The API does a really good job of implementing this (unless you want some specific functionality).

Second, the method notifyObservers() is overloaded so that you can pass it an object, IE notifyObservers(Object obj). If you pass it your Pet, notifyObservers(this), then you will have a reference to your Pet object that is being observed.

I think this is your question but please correct me if I am wrong.

EDIT: To clarify, my answer is contingent upon you using the Observable class in the Java API here.

Upon further review, you should already have a reference to the Pet object that called the update method of the Observer

这篇关于可观察/观察的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆