fragment继承FragmentPagerAdapter,在Activity获取其中某个fragment的控件的代码
时间: 2023-06-19 22:08:28 浏览: 55
可以通过FragmentPagerAdapter中的getItem方法获取指定位置的Fragment实例,进而获取其中的控件。具体代码如下:
```java
public class MyAdapter extends FragmentPagerAdapter {
// Fragment集合
private List<Fragment> mFragments = new ArrayList<>();
public MyAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
```
在Activity中获取第一个Fragment中的某个控件:
```java
// 获取第一个Fragment中的TextView
MyAdapter adapter = new MyAdapter(getSupportFragmentManager(), fragments);
Fragment fragment = adapter.getItem(0);
TextView textView = fragment.getView().findViewById(R.id.text_view);
```
其中,R.id.text_view为需要获取的控件的id。同理,可以通过getItem方法获取其他位置的Fragment实例,进而获取其中的控件。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)