Android中在一个fragment中设置另一个fragment的textview
时间: 2024-01-22 10:20:20 浏览: 176
可以通过在父Fragment中获取子Fragment的方式来实现。具体步骤如下:
1. 在父Fragment中获取子Fragment的实例。假设子Fragment的id为childFragment。
```
ChildFragment childFragment = (ChildFragment) getChildFragmentManager().findFragmentById(R.id.childFragment);
```
2. 在父Fragment中调用子Fragment中的方法来设置TextView的值。假设子Fragment中有一个名为setText的公共方法来设置TextView的值。
```
childFragment.setText("Hello World");
```
完整的示例代码如下:
```
public class ParentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
ChildFragment childFragment = (ChildFragment) getChildFragmentManager().findFragmentById(R.id.childFragment);
childFragment.setText("Hello World");
return view;
}
}
public class ChildFragment extends Fragment {
private TextView mTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.textView);
return view;
}
public void setText(String text) {
mTextView.setText(text);
}
}
```
阅读全文