Activity中访问Fragment中的控件
时间: 2024-03-26 18:34:19 浏览: 22
在Activity中访问Fragment中的控件,可以通过Fragment中的getView()方法获取Fragment的视图,然后在视图中查找控件。
具体步骤如下:
1. 在Fragment中,重写onCreateView()方法,在方法中加载布局并返回视图:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
return view;
}
```
2. 在Activity中,通过FragmentManager获取Fragment实例,并调用getView()方法获取Fragment的视图:
```
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
View fragmentView = fragment.getView();
```
3. 在Fragment的视图中查找控件:
```
TextView textView = fragmentView.findViewById(R.id.text_view);
```
这样就可以在Activity中访问Fragment中的控件了。需要注意的是,如果Fragment还未添加到Activity中,在获取Fragment实例时需要使用FragmentManager的findFragmentByTag()或findFragmentById()方法。如果Fragment已经添加到Activity中,可以直接使用getSupportFragmentManager()获取FragmentManager实例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)