Android 片段中的 findViewById
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12536125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
findViewById within fragment
提问by Peri Hartman
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.
有没有办法在片段范围内通过 id 查找视图?我正在使用一系列片段来呈现一个专门的列表。这些片段是从布局加载的,因此它们的小部件都具有相同的 ID。
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.
我想我可以想出一种方法,在创建期间(或之后)为每个小部件提供一个自定义 ID。但是,如果我能以某种方式将 findViewById 限制在片段的范围内,那就更好了。
回答by chris-tulip
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;
}
回答by Michael Celey
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);
回答by 500865
You can do it by getView().findViewById()
你可以通过 getView().findViewById()
回答by slezadav
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(...);
是的,有办法,可以通过rootView找到。首先找到你的片段的 rootViewrootView=getView();
然后使用rootView.findViewById(...);
回答by sms247
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);
}