如果我有一个函数不时获取不同的值,并且使用片段作为显示,我想随着值的变化更新片段内的 TextView,我该如何从 MainActivity 中的片段操作 TextView?
要澄清更多:
My MainActivity 验证 DatabaseReference 中的值,如下所示:
userLoggedInRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (!dataSnapshot.child("office").getValue(String.class).equals("none")) {
officeKeyLoggedIn = dataSnapshot.child("office").getValue(String.class);
usersInOffice.child(officeKeyLoggedIn).child(userKey).setValue("").addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
/new-code/
}
}
});
}
...
因此,当用户进入办公室并且值从"none"更改为"/officeKey/"时,这是条件,此时我想调用"/new-code/"片段,这是 MainActivity 的显示,将隐藏 TextView 的可见性设置为可见并将其文本设置为通知用户他现在已登录的内容。
我怎样才能做到这一点?
编辑1:主要活动片段
In You Activity
您必须初始化此片段(例如作为字段(:
public class MainActivity extends AppCompatActivity {
// Instance of our fragment
OwnFragment fragment = new OwnFragment();
}
请记住将此实例用于事务(使用
FragmentManager
(
在片段中:
接下来,在片段中,您可以创建接收数据的新方法:
public class OwnFragment extends Fragment {
// So you can pass there: View.VISIBLE, View.GONE or View.INVISIBLE
void setVisibility(int visibility) {
textView.setVisibility(visibility);
}
// Your new method
void setNewText(String text) {
textView.setText(text);
}
}
再次在活动中:
你可以使用上面的片段实例调用此方法:
fragment.setNewText("Hello world");