【问题标题】:how to transfer data from an activty to a fragment? [duplicate]如何将数据从活动传输到片段? [复制]
【发布时间】:2017-06-03 16:17:00
【问题描述】:

我是 android 的初学者。我正在尝试找到一种将文本从活动的editText传输到片段的方法,以便结果显示在片段的文本视图中。

【问题讨论】:

  • 你应该真正使用 Fragment 作为整个 UI 和 EditText 本身。

标签: android android-fragments android-activity


【解决方案1】:

您可以使用 bundle 将数据从活动传输到片段

我想数据将在按钮点击时发送。

Bundle bundle = new Bundle();
bundle.putString("from_activity", edittext.getText().toString());
Fragmentclass fragment= new Fragmentclass();
fragment.setArguments(bundle);

在片段中

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view;
    view=inflater.inflate(R.layout.fragment, container, false);

    String text= getArguments().getString("from_activity"); 
  TextView tv=(TextView)findViewById(R.id.yourTextView);
   tv.setText(text);   
    return view;
}

【讨论】:

  • 这使用了一个硬编码的字符串,而不是像问的问题那样来自 EditText 的值
  • 根据需要更正:)
  • 好吧,除了 edittext.getText().toString() 在视图加载时为空
  • @cricket_007 edittext.getText().toString() 将在按钮单击时执行。它不会为空。
  • 如果在按钮单击操作中执行,它不会为空,如果我错了,请纠正我。
猜你喜欢
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2021-07-23
相关资源
最近更新 更多