findViewById within fragment

感情迁移 提交于 2019-11-27 11:36:44

问题


Is there any way to find a view by id within the scope of a fragment? I'm using a series of fragments to render a specialized list. The fragments are loaded from a layout, so their widgets all have the same ids.

I suppose I can figure out a way to give each widget a custom id during (or right after) creation. However, it would be a lot nicer if I could somehow limit the findViewById to the scope of the fragment.


回答1:


private View myFragmentView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
    myView = myFragmentView.findViewById(R.id.myIdTag)

    return myFragmentView;
}



回答2:


From inside the Fragment:

getView().findViewById(R.id.your_view);

From the enclosing Activity:

getFragmentManager().findFragmentByTag("YourFragmentTag").getView().findViewById(R.id.your_view);

or

getFragmentManager().findFragmentById(R.id.your_fragment).getView().findViewById(R.id.your_view);



回答3:


You can do it by getView().findViewById()




回答4:


Yes, there is a way, you can find it through rootView. First find the rootView of your fragment rootView=getView(); and then use rootView.findViewById(...);




回答5:


  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootview=null;

             rootview=inflater.inflate(R.layout.fragment_web_view, container, false);
           ListView lv = (ListView)rootview.findViewById(android.R.id.list);

return rootview;
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_web_view, container, false);
    }


来源:https://stackoverflow.com/questions/12536125/findviewbyid-within-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!