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


当前回答

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

}

其他回答

根据API级别11的文档

参考,在Back Stack http://developer.android.com/reference/android/app/Fragment.html

短代码

/**
 * The Fragment's UI is just a simple text view showing its
 * instance number.
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.hello_world, container, false);
    View tv = v.findViewById(R.id.text);
    ((TextView)tv).setText("Fragment #" + mNum);
    tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
    return v;
}

方法getView()不会在OnCreate和类似方法之外的片段上工作。

你有两种方法,将视图传递给oncreate上的函数(这意味着你只能在创建视图时运行你的函数)或将视图设置为变量:

private View rootView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
}

public void doSomething () {
    ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
}

使用gradle skeleton插件,它会自动生成视图持有者类,并引用到你的布局。

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MyLayout myLayout = new MyLayout(inflater, container, false);
        myLayout.myImage.setImageResource(R.drawable.myImage);
        return myLayout.view;
    }
}

现在假设你在my_layout.xml文件中声明了一个ImageView,它会自动为你生成myLayout类。

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

注意,如果你使用getView()方法,它可能会导致nullPointerException,因为它返回根视图,它将是onCreateView()方法之后的某个视图。

还有一个方法叫做onViewCreated。

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
}