英文:
How can I create dynamically a TextView simultaneously in two activities in android studio?
问题
I have two activities, in activityOne the user will dynamically create textViews and I want that in the same time to dynamically create textViews with the same content inside activityTwo.
For example:
In activityOne the user will dynamically create a textView "Groceries" I want that in the same time in activityTwo to be dynamically created a textView with the same name: "Groceries".
英文:
I have two activities, in activityOne the user will dynamically create textViews and I want that in the same time to dynamically create textViews with the same content inside activityTwo.
For example:
In activityOne the user will dynamically create a textView "Groceries" I want that in the same time in activityTwo to be dynamically created a textView with the same name: "Groceries".
答案1
得分: 0
以下是代码的中文翻译部分:
您可以使用数据仓库类如下所示:
public class DataRepository {
private static final DataRepository INSTANCE = new DataRepository();
private final MutableLiveData<String> text = new MutableLiveData<>();
public void updateText(String newText){
text.setValue(newText);
}
public MutableLiveData<String> getText() {
return text;
}
public static DataRepository getInstance(){
return INSTANCE;
}
}
然后,您可以使用类似以下方式的 Observer
来监听数据的变化:
DataRepository dataRepository = DataRepository.getInstance();
dataRepository.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(String newText) {
textView.setText(newText);
}
});
其中,this
指的是 Activity。
要更新文本,只需在程序的任何地方调用如下:
DataRepository dataRepository = DataRepository.getInstance();
dataRepository.updateText("新文本");
观察者会自动更新所有内容。
英文:
You can use a data repository class as such
public class DataRepository {
private static final DataRepository INSTANCE = new DataRepository();
private final MutableLiveData<String> text = new MutableLiveData<>();
public void updateText(String newText){
text.setValue(newText);
}
public MutableLiveData<String> getText() {
return text;
}
public static DataRepository getInstance(){
return INSTANCE;
}
}
You can then listen to changes on the data using an Observer
like so
DataRepository dataRepository = DataRepository.getInstance();
dataRepository.getText().observe(this, new Observer<String>() {
@Override
public void onChanged(String newText) {
textView.setText(newText);
}
});
Where this
refers to the Activity.
To update the text, simply call
DataRepository dataRepository = DataRepository.getInstance();
dataRepository.updateText("New text");
From anywhere in your program. The observers will update everything for you automatically.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论