次のように、スピナーにカスタム行レイアウトを使用しようとしています:
String[] countryArr={"USA","Canada","Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.row, R.id.text, countryArr);
spinnerCountry.setAdapter(adapter);
行.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingTop="10dp" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/BLACK"
android:textSize="26dp" />
<RadioButton
android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
および Java コード:
spinnerCountry.setOnItemSelectedListener(new MyOnItemSelectedListener());
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
selected = parent.getItemAtPosition(pos).toString().trim();
Log.i("MyOnItemSelectedListener","selected ="+selected);
}
@SuppressWarnings("rawtypes")
public void onNothingSelected(AdapterView parent) {
etCountry.setText("");
Log.i("MyOnItemSelectedListener","nothing selected");
}
}
アプリを起動すると、ログにこれが表示され"selected =Other"
ます。これはデフォルトであるためです。
しかし、スピナーをクリックすると、次のような画面が表示されてonItemSelected
機能しません。そのため、アラート ボックスが常に表示され、3 つの値すべてを選択できますが、アクションは実行されません。
main.xml
<com.Mypackage.MySpinner
android:id="@+id/SpinnerCountry1"
android:layout_width="45dp"
android:layout_height="59dp"
android:layout_marginLeft="160dp"
android:background="@drawable/selector_slim_spinner"
android:clickable="true"
android:entries="@array/blankarray" />
public class MySpinner extends Spinner {
private Context _context;
public MySpinner(Context context, AttributeSet attrs) {
super(context, attrs);
_context = context;
}
public MySpinner(Context context) {
super(context);
_context = context;
}
public MySpinner(Context context, AttributeSet attrs, int defStyle) {
super(context);
_context = context;
}
@Override
public View getChildAt(int index) {
View v = new View(_context);
return v;
}
}
スピナーにカスタム行レイアウトを使用しない場合、正常に動作することに注意してくださいOnItemSelected
。
どんな助けでも感謝します。