簡體   English   中英

Android在變量上執行代碼

[英]Android execute code on variable change

我在不同的按鈕點擊上改變一個變量(即在多個按鈕的onclick監聽器內部),我有一個textview,假設顯示這個變量,但仍然在監聽器代碼之外。

textview不會更新變量,所以我想我可能需要一個'onclick'處理程序版本的變量。

我該怎么做呢?

當變量或類字段發生更改時,無法通知Java。 您需要做的是為int實現一個簡單的包裝類,以便客戶端可以在值發生變化時注冊回調。 這個類看起來像這樣:

package com.example.android;

/**
 * A store of an int value. You can register a listener that will be notified
 * when the value changes.
 */
public class IntValueStore {

    /**
     * The current value.
     */
    int mValue;

    /**
     * The listener (you might want turn this into an array to support many
     * listeners)
     */
    private IntValueStoreListener mListener;

    /**
     * Construct a the int store.
     *
     * @param initialValue The initial value.
     */
    public IntValueStore(int initialValue) {
        mValue = initialValue;
    }

    /**
     * Sets a listener on the store. The listener will be modified when the
     * value changes.
     *
     * @param listener The {@link IntValueStoreListener}.
     */
    public void setListener(IntValueStoreListener listener) {
        mListener = listener;
    }

    /**
     * Set a new int value.
     *
     * @param newValue The new value.
     */
    public void setValue(int newValue) {
        mValue = newValue;
        if (mListener != null) {
            mListener.onValueChanged(mValue);
        }
    }

    /**
     * Get the current value.
     *
     * @return The current int value.
     */
    public int getValue() {
        return mValue;
    }

    /**
     * Callbacks by {@link IntValueModel}.
     */
    public static interface IntValueStoreListener {
        /**
         * Called when the value of the int changes.
         *
         * @param newValue The new value.
         */
        void onValueChanged(int newValue);
    }
}

現在您需要一些實現IntValueStoreListener接口的類。 你可以讓它成為Activity ,然后跟蹤要更新的TextView 我會實現一個簡單的自定義TextView ,如下所示:

package com.example.android;

import com.example.android.IntValueStore.IntValueStoreListener;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class IntTextView extends TextView implements IntValueStoreListener{

    public IntTextView(Context context) {
        super(context);
    }

    public IntTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void onValueChanged(int newValue) {
        // The int got a new value! Update the text
        setText(String.valueOf(newValue));
    }
}

您現在可以設置布局XML。 例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_increment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Increment" />

    <Button
        android:id="@+id/btn_double"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Double" />

    <com.example.android.IntTextView
        android:id="@+id/text_current_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

執行必要設置的活動如下所示:

package com.example.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class IntValueStoreActivity extends Activity {

    private IntValueStore mIntValueModel = new IntValueStore(1);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Initialize the text view with the initial value
        IntTextView intTextView = (IntTextView)findViewById(R.id.text_current_value);
        intTextView.setText(String.valueOf(mIntValueModel.getValue()));

        // Setup the text view as a listener so it gets updated whenever the int
        // value changes
        mIntValueModel.setListener(intTextView);

        // Setup an OnClickListener that will increment the int value by 1. The
        // TextView will be automatically updated since it is setup as a
        // listener to the int value store
        findViewById(R.id.btn_increment).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mIntValueModel.setValue(mIntValueModel.getValue() + 1);
            }
        });

        // Setup an OnClickListener that will double the int value. The TextView
        // will be automatically updated since it is setup as a listener to the
        // int value store
        findViewById(R.id.btn_double).setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mIntValueModel.setValue(mIntValueModel.getValue() * 2);
            }
        });
    }
}

這將為您提供以下UI:

應用截圖

每當您單擊任何按鈕時, TextView幾乎會神奇地更新它顯示的值,即使OnClickListeners沒有任何代碼可以觸摸TextView

這實際上是編程中常見的模型,稱為模型 - 視圖 - 控制器 在上面的示例代碼中,Model是IntValueStore ,View是IntTextView ,沒有Controller。

在C#中,有一種簡單的方法可以在變量發生變化時觸發某些操作,因此它在Java中。 Java afaik不支持運算符重載,但此功能不是必需的。 當涉及面向類(對象)的編程時,只需從任何標准類型創建您的特殊類型。 新類將擴展任何類型的函數(int,long,string等)。 定義,例如你自己的“SET”和/或“GET”方法,只使用這些而不是標准的“=”或獲取值/ ponter作為左操作數。

例:

public class myINT
{
 public int Value;

 public void SET(int v) {Value = v;  // PLUS additional ACTION }
 public int  GET(int v) {return Value ;}
 public void ADD(int v) {Value += v; // PLUS additional ACTION }
 public void SUB(int v) {Value -= v; // PLUS additional ACTION }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM