Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

android - 片段中的findViewById(findViewById in Fragment)

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment.

(我试图在一个Fragment中创建一个ImageView,该ImageView引用我在Fragment的XML中创建的ImageView元素。)

However, the findViewById method only works if I extend an Activity class.

(但是,仅当我扩展Activity类时, findViewById方法才有效。)

Is there anyway of which I can use it in Fragment as well?

(无论如何,我也可以在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);
    }
}

The findViewById method has an error on it which states that the method is undefined.

(findViewById方法上有一个错误,指出该方法未定义。)

  ask by simplified. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use getView() or the View parameter from implementing the onViewCreated method.

(使用getView()或实现onViewCreated方法的View参数。)

It returns the root view for the fragment (the one returned by onCreateView() method) .

(它返回片段的根视图(由onCreateView()方法返回的片段 。)

With this you can call findViewById() .

(这样,您可以调用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); 

As getView() works only after onCreateView() , you can't use it inside onCreate() or onCreateView() methods of the fragment .

(由于getView()仅在onCreateView()之后才起作用,因此您不能在片段的onCreate()onCreateView()方法使用它 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...