android - fragment 中的 findViewById

标签 android android-fragments android-imageview findviewbyid

我正在尝试在 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 方法有一个错误,指出该方法未定义。

最佳答案

使用 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() 中使用它 fragment 的code>onCreateView()方法

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

相关文章:

java - onKeyListener 未在 Android 中触发事件

android - ListView回收图片

java - 解密错误: Pad block corrupted

android - 如何创建 CDMA 类型 radio 的 Android 模拟器?

java - fragment 设计

Android ImageView 修复图像大小

android - ImageView.ScaleType.FitXY 在代码中不起作用

android - adb 安装失败并显示消息 Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE] 即使在重新启动系统和模拟器之后也是如此

java - 为 Android 上的 SSH 登录生成 RSA 私钥/公钥对

android - 第二次选择 fragment 时显示空白屏幕