Android笔记:如何在Fragment里使用findViewById()方法?

在Activity中,可以直接用findViewById(int id),通过xml的id来找到对应的View。

查找官方的api,具体如下:

https://developer.android.google.cn/reference/android/app/Activity.html#findViewById(int)

 

而在Fragment中,直接使用会报错如下:

The method findViewById(int) is undefined for the type Fragment

可以在onCreateView()中借助view来调用这个方法,查找官方的api如下所示:

https://developer.android.google.cn/reference/android/view/View.html#pubmethods

 

总结:Activity、View都有findViewById(int id)这个方法,而Fragment没有,只能通过View来调用findViewById(int id)

具体代码如下所示:

public class LanguageFragment extends Fragment{
    private TextView mTextView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_language, container,false);
        mTextView=(TextView)view.findViewById(R.id.language); 
        return view;
    }
  
}

 

posted on 2017-01-03 15:03  乐之者v  阅读(2413)  评论(0编辑  收藏  举报

导航