简体   繁体   English

如何像 React.js 一样在 Java 中进行实时值更改

[英]How to do a realtime value change in Java like React.js

I got used to React.js for 6 months and starting to develop an app from Java scratch for my Android application.我已经习惯了React.js 6 个月,并开始从 Java 为我的 Android 应用程序开发一个应用程序。

In React.js , All it does when the boolean changed from false to true:React.js中,当 boolean 从 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
}

If the checkmarkChecked was switched to true, it calls the true one to show.如果 checkmarkChecked 被切换为 true,它会调用 true 来显示。

Now I am new to Java for Android development, i tried one of these:现在我是 Java 的新手,用于 Android 开发,我尝试了其中一种:

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

Actually, the while(true) causes my app to freeze at the start.实际上,while(true) 导致我的应用程序在开始时冻结。

You may use a MutableLiveData that wraps a Boolean , and register the activity to observe it with .observe() .您可以使用封装了MutableLiveDataBoolean ,并使用.observe()注册活动以观察它。

Whenever this boolean value changes, then onChanged() callback will be triggered with the new value of the boolean.每当此 boolean 值更改时,将使用 boolean 的新值触发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());
            }
        });
        
    }
}

The button just for toggling the boolean value to test it仅用于切换 boolean 值以对其进行测试的按钮

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM