如何通过context 获取 类
时间: 2023-09-05 12:10:55 浏览: 50
如果你想要获取`Context`所在的`Activity`的类,可以使用以下代码:
```
if (context instanceof Activity) {
Class<? extends Activity> activityClass = context.getClass();
// 进行操作
}
```
在上面的代码中,首先判断`Context`是否是`Activity`的实例,如果是,则通过`getClass()`方法获取该`Activity`的类。
如果你想要获取`Context`所在的`Fragment`的类,可以使用以下代码:
```
if (context instanceof FragmentActivity) {
FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
for (Fragment fragment : fragmentManager.getFragments()) {
if (fragment != null && fragment.isVisible()) {
Class<? extends Fragment> fragmentClass = fragment.getClass();
// 进行操作
}
}
}
```
在上面的代码中,首先判断`Context`是否是`FragmentActivity`的实例,如果是,则通过`getSupportFragmentManager()`方法获取该`FragmentActivity`所管理的`FragmentManager`对象,然后遍历该`FragmentManager`中的所有`Fragment`,找到当前可见的`Fragment`,再通过`getClass()`方法获取该`Fragment`的类。
需要注意的是,获取`Context`所在的`Fragment`的类,需要在`Fragment`所依附的`Activity`的`onCreate()`方法执行完毕后才能调用,否则可能会返回`null`。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)