【问题标题】:Retain text in a TextView on rotation旋转时在 TextView 中保留文本
【发布时间】:2019-06-02 04:02:12
【问题描述】:

我有两个片段TestOneFragment 是默认片段,TestTwoFragment 添加到后堆栈。当我在TestTwoFragment 处于前景时旋转屏幕时,文本也应该保持不变。

这是我的 Fragment 中的 onCreateView 方法

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    viewHolder = inflater.inflate(R.layout.fragment_test_two, container, false)

    arguments?.getString("msg").run {
        if (this != null)
            viewHolder.tvFragTestTwo.text = this
        else
            viewHolder.tvFragTestTwo.text = "NO BUTTONS CLICKED"
    }

    listener.onCreateListener(viewHolder.tvFragTestTwo.text.toString())

    return viewHolder
}

我创建了一个接口OnCreateListener,以便我可以在父活动中使用 textView。这是该接口的实现。

override fun onCreateListener(string: String) {
    val bundle = Bundle()
    bundle.putString("msg", string)
    testTwoFragment.arguments = bundle
}

每次屏幕旋转时,文本设置为默认值。

【问题讨论】:

    标签: android android-studio android-fragments fragment


    【解决方案1】:

    我添加了 android:configChanges="orientation|screenSize" 在清单文件中的相应活动标签中,它对我有用。

    【讨论】:

      【解决方案2】:

      每次您旋转屏幕时,Android 都会销毁并重新创建绑定到您的片段的 Activity。为了将文本保留在文本视图中,您应该将信息保存在 onSaveInstanceState 方法中,并在 onActivityCreated 方法中恢复保存的信息。

      public class MainFragment extends Fragment {
      
          // These variable are destroyed along with Activity
          private String text;
      
          ...
      
          @Override
          public void onSaveInstanceState(Bundle outState) {
              super.onSaveInstanceState(outState);
              outState.putInt("your_text_id", text); // this text comes from your textview
          }
      
          @Override
          public void onActivityCreated(@Nullable Bundle savedInstanceState) {
              super.onActivityCreated(savedInstanceState);
              text = savedInstanceState.getString("your_text_id");
          }
      
      }
      

      【讨论】:

      • 我试过这个。但是没有从片段中调用 onSaveInstanceState()。
      • @VishakAKamath 发布您的活动和片段的代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多