如何在类似React.js的Java中进行实时值更改



我已经习惯了React.js6个月,并开始为我的Android应用程序从头开始开发一个应用程序。

React.js中,当布尔值从false变为true时所做的一切:

this.state = {
checkmarkChecked: false
}
if (this.state.checkmarkChecked) {
//If the checkmarkChecked is true
//TODO: show all checks
} else {
//If the checkmarkChecked is false
//TODO: hide all checks
}

如果选中标记Checked切换为true,则调用true来显示。

现在我是Java Android开发的新手,我尝试了其中一个:

//onCreate
while (true) {
if (checkmarkChecked) {
System.out.println("True");
} else {
System.out.println("False");
}
}

事实上,while(true(导致我的应用程序在启动时冻结。

您可以使用包装BooleanMutableLiveData,并注册活动以使用.observe()观察它。

每当该布尔值发生变化时,就会使用该布尔值的新值触发onChanged()回调。

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MutableLiveData<Boolean> state = new MutableLiveData<>(false);

state.observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean newValue) {
if (newValue) {
Toast.makeText(MainActivity.this, "True", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "False", Toast.LENGTH_SHORT).show();
}
}
});

Button myButton = findViewById(..);

myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
state.setValue(!state.getValue());
}
});

}
}

只用于切换布尔值以测试的按钮

最新更新