[英]Detecting when a value changed in a specific variable in Android
I have an int
variable called mCurrentIndex
. 我有一个名为mCurrentIndex
的int
变量。 I want to do something when its value changes. 当值改变时,我想做一些事情。
For example: 例如:
public class MainActivity extends Activity{
private int mCurrentIndex = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Apps logic.
}
public onCurrentIndexValueChange(){
button.setClickable(true);
}
}
If the scope on mCurrentIndex is only in MainActivity then I think it would be best just to create getter and setter methods for mCurrentIndex and at the end of the setter method call onCurrentIndexValueChange() 如果mCurrentIndex的作用域仅在MainActivity中,那么我认为最好是为mCurrentIndex创建getter和setter方法,并在setter方法的末尾调用onCurrentIndexValueChange()
public int getIndex(){
return this.mCurrentIndex;
}
public void setIndex(int value){
this.mCurrentIndex = value;
this.onCurrentIndexValueChange();
}
you can use a setter function 您可以使用设置器功能
private int mCurrentIndex = 1;
public void setCurrentIndex(int newValueFormCurrentIndex)
{
if(newValueFormCurrentIndex != mCurrentIndex)
{
onCurrentIndexValueChange();
mCurrentIndex = newValueFormCurrentIndex;
}
}
One approach to solving this is using Android's LiveData . 解决此问题的一种方法是使用Android的LiveData 。
In your situation, since you'd like to observe an int
, you can do something like this: 在您的情况下,由于您想观察一个int
,因此可以执行以下操作:
public MutableLiveData<Integer> mCurrentIndex = new MutableLiveData<>();
To change your value, you would do this: 要更改您的价值,您可以这样做:
mCurrentIndex.setValue(12345); // Replace 12345 with your int value.
To observe the changes you would do the following : 要观察更改,您可以执行以下操作 :
mCurrentIndex.observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable final Integer newIntValue) {
// Update the UI, in this case, a TextView.
mNameTextView.setText("My new current index is: " + newIntValue);
}
};);
}
This approach is useful because you can define a ViewModel to segregate your logic from your Activity while having the UI observe and reflect the changes that occur. 这种方法很有用,因为您可以定义一个ViewModel来将您的逻辑与Activity隔离开,同时让UI观察并反映发生的更改。
By separating your logic out to the ViewModel, your logic becomes more easily testable since writing tests for your ViewModel is relatively easier than writing tests for your Activity. 通过将您的逻辑分离到ViewModel,您的逻辑变得更易于测试,因为为ViewModel编写测试比为Activity编写测试相对容易。
For more information on LiveData check out this link . 有关LiveData的更多信息,请查看此链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.