[英]Android Spinner's onItemSelected executed twice when going back to Fragment
[英]onItemSelected not trigged when it is included in a fragment
===根本原因===
onItemSelected的方法不錯,對於下面我要描述的問題,原因是我只是將一些代碼分支到ArrayAdapter.notifyDataSetInvalidated()。 給我的教訓是:
*當AdapterView上發生“無響應”時,請檢查適配器。
感謝給我任何建議的朋友。
===================
我想在片段中放入微調框,但是onItemSelected無法正常工作,請您告訴我原因,非常感謝。
這是活動布局xml:
<LinearLayout>
<!-- onItemSelected works fine when the spinnerConnector defined in activity layout -->
<Spinner
android:id="@+id/spinnerConnectors"
android:spinnerMode="dropdown" />
<!-- move spinnerConnectors into this fragment will cause the problem - onItemSelected not work
<fragment
android:id="@+id/fragmentConnectors"
android:name="com.sharework.transproxy.android.ConnectorsFragment"
tools:layout="@layout/list_fragment1" />
-->
</LinearLayout>
連接器片段
public class ConnectorsFragment extends android.app.Fragment{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create adapter ...
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.connectors_fragment, null);
Spinner spinnerConnectors = (Spinner) view
.findViewById(R.id.spinnerConnectors);
spinnerConnectors.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
Spinner spinnerConnectors = (Spinner) getView().findViewById(
R.id.spinnerConnectors);
spinnerConnectors
.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// **** code to handle onItemSelected but not trigged
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
連接器的布局
<LinearLayout>
<Spinner
android:id="@+id/spinnerConnectors"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown" />
</LinearLayout>
活動
public class FactoryMonitorActivity TransProxyActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_factory_monitor);
// invoke ConnectorsFragment.start to query for connectors and fill into the adapter
}
}
可以幫助任何人,謝謝!
從“活動”中刪除與微調器相關的所有內容(也許您在測試期間錯過了刪除操作),然后使spinnerConnectors
成為該片段的類變量。 因此,您只需要為視圖查找一次(此操作會影響性能),並且下次您使用微調器時,不必在方法內聲明局部變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.