我试图在一个片段中创建一个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方法有一个错误,说明该方法未定义。
在onCreateView方法中
1)首先你必须膨胀你想要添加的布局/视图
如。LinearLayout
LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);
2)然后你可以从布局中找到你的imageView id
ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);
3)返回膨胀的布局
return ll;
在Fragment类中,你会得到onViewCreated()覆盖方法,你应该总是初始化你的视图,因为在这个方法中,你得到视图对象,使用它你可以像这样找到你的视图:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
永远记住,在Fragment的情况下,如果你从onCreateView()方法返回null或super.onCreateView(), onViewCreated()方法不会自动调用。
它将在ListFragment作为ListFragment返回FrameLayout的情况下被默认调用。
注意:一旦onCreateView()成功执行,你可以使用getView()在类的任何地方获得片段视图。
即。
getView().findViewById("your view id");
我知道这是一个老问题,但普遍的答案让人感到有些不足。
问题是不清楚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;
}
}
你也可以在onActivityCreated方法中做。
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
就像他们在这里做的:http://developer.android.com/reference/android/app/Fragment.html(在API级别28中已弃用)
getView().findViewById(R.id.foo);
and
getActivity().findViewById(R.id.foo);
是有可能的。
在Fragment类中,我们得到onViewCreated()重写方法,我们应该总是初始化我们的视图,因为在这个方法中我们得到视图对象。使用这个对象,我们可以像下面这样找到我们的视图:
class MyFragment extends Fragment {
private ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//initialize your view here for use view.findViewById("your view id")
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}