我有一个int名为 的变量mCurrentIndex。当它的值发生变化时我想做一些事情。
例如:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
解决这个问题的一种方法是使用Android 的 LiveData。
在你的情况下,因为你想观察 an int,你可以这样做:
public MutableLiveData<Integer> mCurrentIndex = new MutableLiveData<>();
Run Code Online (Sandbox Code Playgroud)
要更改您的值,您可以这样做:
mCurrentIndex.setValue(12345); // Replace 12345 with your int value.
Run Code Online (Sandbox Code Playgroud)
要观察更改,您需要执行以下操作:
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);
}
};);
}
Run Code Online (Sandbox Code Playgroud)
这种方法很有用,因为您可以定义一个 ViewModel 将逻辑与 Activity 分离,同时让 UI 观察并反映发生的更改。
通过将逻辑分离到 ViewModel,您的逻辑变得更容易测试,因为为 ViewModel 编写测试比为 Activity 编写测试相对容易。
有关 LiveData 的更多信息,请查看此链接。