我试图在onViewCreated
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
date = (TextView) view.findViewById(R.id.textDate);
date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
}
如果视图是第一次,请设置这两行:
date = (TextView) view.findViewById(R.id.textDate);
date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
我是否有其他方法可能没有想到和错过,或者if语句是更可行的方法。
以下是代码的其余部分:
public class Notifications extends Fragment {
TextView servingqueue;
TextView date;
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mServingQueue = mRootRef.child("ServingQueue");
public Notifications() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mServingQueue.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Double number = dataSnapshot.getValue(Double.class);
servingqueue.setText(String.valueOf(number));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notifications, container, false);
// Inflate the layout for this fragmentid.queueServing);
servingqueue = (TextView) rootView.findViewById(R.id.queueServing);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
date = (TextView) view.findViewById(R.id.textDate);
date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
}
}
答案 0 :(得分:0)
如果您只想将设置为第一个时间,则可以检查savedInstanceState
是否为空。如果它为空,则整个Fragment
都是新品牌。如果它不为空,那么您将从屏幕旋转或其他内容返回。
但是,你的TextView会突然变空,因为它会被创建,所以这是另一种选择。
在onSaveInstanceState
中,保存TextView
的状态,
@Override
public void onSaveInstanceState(Bundle b) {
super.onSaveInstanceState(b);
b.putString("DATE_TEXT", date.getText().toString());
}
然后,在onViewCreated()
中,检索文字如下:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String dateText = (savedInstanceState != null) ?
savedInstanceState.getString("DATE_TEXT") :
DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
date = (TextView) view.findViewById(R.id.textDate);
date.setText(DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
}