• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

android - fragment 中的 findViewById

[复制链接]
菜鸟教程小白 发表于 2022-8-1 01:25:42 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试在 Fragment 中创建一个 ImageView,它将引用我在 XML 中为 Fragment 创建的 ImageView 元素。但是,findViewById方法仅在我扩展 Activity 类时才有效。无论如何,我也可以在 Fragment 中使用它吗?

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ImageView imageView = (ImageView)findViewById(R.id.my_image);
        return inflater.inflate(R.layout.testclassfragment, container, false);
    }
}
findViewById方法上有一个错误,指出该方法未定义。



Best Answer-推荐答案


使用getView()或来自实现 onViewCreated 的 View 参数方法。它返回 fragment 的 Root View (onCreateView() 方法返回的那个) .有了这个你可以调用findViewById() .

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
    // or  (ImageView) view.findViewById(R.id.foo); 

getView()仅在 onCreateView() 之后有效,你里面不能用onCreate()onCreateView()方法的 fragment 。

关于android - fragment 中的 findViewById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6495898/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap