activity中通过FrameLayout加载fragment并在activity中传入String到fragment,更新fragment的textview内容
时间: 2024-06-03 14:12:04 浏览: 16
好的,这个问题属于技术问题,可以回答。
实现方式如下:
首先在activity中创建一个 FrameLayout,然后通过 FragmentManager 加载相应的 Fragment。
在加载 Fragment 的时候,可以通过 Bundle 将需要传递的 String 信息打包传递给 Fragment,然后在 Fragment 中获取 Bundle 中的信息并更新 TextView 的内容。
示例代码如下:
// 在 activity 中加载 Fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
ExampleFragment fragment = ExampleFragment.newInstance("这是我想传递的字符串");
transaction.replace(R.id.frameLayout, fragment);
transaction.commit();
// 在 Fragment 中获取传递过来的字符串并更新 TextView 的内容
public class ExampleFragment extends Fragment {
public static ExampleFragment newInstance(String exampleString) {
ExampleFragment fragment = new ExampleFragment();
Bundle args = new Bundle();
args.putString("exampleString", exampleString);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_example, container, false);
Bundle args = getArguments();
if (args != null) {
String exampleString = args.getString("exampleString", "");
TextView textView = view.findViewById(R.id.text_view);
textView.setText(exampleString);
}
return view;
}
}