我试图在一个片段中创建一个ImageView,它将引用我在XML中为片段创建的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方法有一个错误,说明该方法未定义。


当前回答

我喜欢一切都有条理。你可以这样做。

第一个初始化视图

private ImageView imageView;

然后覆盖OnViewCreated

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViews(view);
    }

然后添加一个void方法来查找视图

private void findViews(View v) {
    imageView = v.findViewById(R.id.img);
}

其他回答

布局增压机进入图片这里。布局扩展器是一个使我们能够在java代码中使用XML视图的类。因此,您可以使用以下代码在变量v中扩展根xml视图。然后使用v,你可以找到根视图v的子视图。

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
    return v;
    }
}

你必须放大视图

public class TestClass extends Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
    return v
}}

使用getView()或实现onViewCreated方法的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()方法中使用它。

getView()只在onCreateView()完成后工作,所以从onPostCreate()调用它:

@Override
public void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
}

我知道这是一个老问题,但普遍的答案让人感到有些不足。

问题是不清楚imageView需要什么-我们是将它作为视图传递回去,还是仅仅为以后保存一个引用?

无论哪种方式,如果ImageView来自于膨胀布局,正确的做法是:

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.testclassfragment, container, false);
        ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
        return v;
    }
}