有什麼方法可以在片段的範圍內通過id查找視圖?我正在使用一系列片段來呈現專門的列表。片段從佈局中加載,所以它們的小部件都具有相同的ID。findViewById在片段
我想我可以找出一種方法來在創建過程中(或之後)給每個小部件一個自定義ID。然而,如果我能以某種方式將findViewById限制在片段的範圍內,那將會更好。
有什麼方法可以在片段的範圍內通過id查找視圖?我正在使用一系列片段來呈現專門的列表。片段從佈局中加載,所以它們的小部件都具有相同的ID。findViewById在片段
我想我可以找出一種方法來在創建過程中(或之後)給每個小部件一個自定義ID。然而,如果我能以某種方式將findViewById限制在片段的範圍內,那將會更好。
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;
}
MrFox,請確保你注意到視圖必須被誇大。所以,我會打電話inflater.inflate(v,容器)。那麼,或者你可以做MCeley的第一個建議,但要確保這是在onActivityCreated中完成的,所以View已經被誇大了,等等。否則,如果您在onCreateView中執行此操作時沒有虛增視圖,則會得到一個空指針。 – dennisdrew
對不起!我完全錯過了,因爲我剛從一些代碼中拉出來,並且膨脹超級不好 –
除了在return語句中,我看不到任何對變量'v'的引用。這是一個錯字,如果是的話,它應該是什麼變量? – Spinner
是的,有一種方法,你可以通過rootView找到它。首先找到你的片段rootView=getView();
的rootView然後用rootView.findViewById(...);
您可以通過getView().findViewById()
做到這一點從碎片裏:
getView().findViewById(R.id.your_view);
從封閉活動:
getFragmentManager().findFragmentByTag("YourFragmentTag").getView().findViewById(R.id.your_view);
或
getFragmentManager().findFragmentById(R.id.your_fragment).getView().findViewById(R.id.your_view);
有時getView()爲null,那麼你會怎麼做? – StackOverflowed
在片段調用'onCreateView()'之前,'getView()'僅爲null。此時,沒有視圖可以使用'findViewById()'找到,因爲沒有創建視圖。 – MCeley
@McCley如果在片段被分離後調用getView(),它是否也返回null?我只是很好奇,當一個Fragment的getView()調用返回null。 – StackOverflowed
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);
}
添加您的代碼,它會更容易回答。 – tolgap
[findViewById in Fragment]可能的重複(http://stackoverflow.com/questions/6495898/findviewbyid-in-fragment) – Sufian