为什么TextView在saveInstanceState的片段中不显示“ COUNTER”?

时间:2019-05-05 14:35:58

标签: java android

我想继续显示“计数器”(类型为Int)。如果设备旋转了,碎片会重新加载,但什么也没有显示,但是数据保存在saveInstanceState中。

公共类Timer扩展Fragment {     公共Timer(){

}

View view;
private TextView countDownText;
public int counter=0;
Button bt;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState == null){
        counter=0;
        Toast.makeText(getActivity(), "Counter Value in IF Part : " + counter, Toast.LENGTH_SHORT).show();
    }else{
        counter=savedInstanceState.getInt("Counter",0);
        Toast.makeText(getActivity(), "Counter Value in ELSE part : " + counter, Toast.LENGTH_SHORT).show();

    }
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Toast.makeText(getActivity(), "On Activity Created" + counter, Toast.LENGTH_SHORT).show();
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("Counter",counter);
}


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    Toast.makeText(getContext(), "Fragment loaded...", Toast.LENGTH_SHORT).show();

    view = inflater.inflate(R.layout.timer, container, false);

    countDownText = view.findViewById(R.id.timer);
    bt = view.findViewById(R.id.button);
   //  countDownText.setText(String.valueOf(savedInstanceState.getInt("Counter",0)));

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            counter++;
            countDownText.setText(String.valueOf(counter));

        }
    });

    countDownText.setText(String.valueOf(counter));
    return view;

    }
}

SavedInstanceState显示已存储的数据,但不显示在TextVIew中。

0 个答案:

没有答案