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


当前回答

根据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;
}

其他回答

还有一个方法叫做onViewCreated。

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

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

@Override
public void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
}
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;

}

方法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);
}

你可以调用findViewById()的活动对象,你得到的公共void onAttach(活动活动)方法在你的片段。

将Activity保存为一个变量,例如:

在Fragment类中: private Activity mainActivity; onAttach()方法中: this.mainActivity =活动;

最后通过变量执行每个findViewById: mainActivity.findViewById (R.id.TextView);