10

デフォルトの空の選択項目でスピナーを作成しようとしていますが、スピナーの選択肢から最初の項目が表示されます。スピナーの選択肢のソースである文字列に null 値を追加すると、スピナーを開いた後にその空の行が表示されます。どうすればいいですか?私が使用しているコードは次のとおりです。

  String[] ch = {"Session1", "Session2", "Session3"};
  Spinner sp = (Spinner)findViewById(R.id.spinner1);
  TextView sess_name = findViewById(R.id.sessname);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ch);
  sp.setAdapter(adapter);

  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

  sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener({
      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
          int index = arg0.getSelectedItemPosition();
          sess_name.setText(ch[index]);

          Toast.makeText(getBaseContext(), "You have selected item : " + ch[index], Toast.LENGTH_SHORT).show();
      }
4

5 に答える 5

15

バラクの解決策には問題があります。最初の項目を選択すると、Spinner は OnItemSelectedListener を呼び出しonItemSelected()て空のコンテンツを更新しません。これは、前の位置と選択位置の両方が 0 であるためです。

最初に、文字列配列の先頭に空の文字列を配置します。

String[] test = {" ", "one", "two", "three"};

2 番目のビルド アダプター、変更しないでくださいgetView()、変更しgetDropDownView()ます。空のビューの高さを 1px に設定します。

public class MyArrayAdapter extends ArrayAdapter<String> {

    private static final int ITEM_HEIGHT = ViewGroup.LayoutParams.WRAP_CONTENT;

    private int textViewResourceId;


    public MyArrayAdapter(Context context,
                          int textViewResourceId,
                          String[] objects) {
        super(context, textViewResourceId, objects);
        this.textViewResourceId = textViewResourceId;
    }

    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        TextView textView;

        if (convertView == null) {
            textView = (TextView) LayoutInflater.from(getContext())
                   .inflate(textViewResourceId, parent, false);
        } else {
            textView = (TextView) convertView;
        }

        textView.setText(getItem(position));
        if (position == 0) {
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = 1;
            textView.setLayoutParams(layoutParams);
        } else {
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = ITEM_HEIGHT;
            textView.setLayoutParams(layoutParams);
        }

        return textView;
    }
}
于 2013-03-15T06:06:48.760 に答える
6

私はパーティーに少し遅れていますが、これを解決するために私がしたことは次のとおりです。
ユーザーが初期項目の選択をキャンセルすると、スピナーは初期の空の状態を保持します。最初のアイテムが選択されると、それは「通常」として機能
します 2.3.3 以降で動作しますが、2.2 以下ではテストしていません

最初に、アダプター クラスを作成します...

public class EmptyFirstItemAdapter extends ArrayAdapter<String>{
    //Track the removal of the empty item
    private boolean emptyRemoved = false;

    /** Adjust the constructor(s) to fit your purposes. */
    public EmptyFirstitemAdapter(Context context, List<String> objects) {
        super(context, android.R.layout.simple_spinner_item, objects);
        setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }

    @Override
    public int getCount() {
        //Adjust the count based on the removal of the empty item
        if(emptyRemoved){
            return super.getCount();            
        }
        return super.getCount()-1;            
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(!emptyRemoved){
            // Remove the empty item the first time the dropdown is displayed.
            emptyRemoved = true;
            // Set to false to prevent auto-selecting the first item after removal.
            setNotifyOnChange(false);
            remove(getItem(0));
            // Set it back to true for future changes.
            setNotifyOnChange(true);
        }
        return super.getDropDownView(position, convertView, parent);
    }

    @Override
    public long getItemId(int position) {
        // Adjust the id after removal to keep the id's the same as pre-removal.
        if(emptyRemoved){
            return position +1;
        }
        return position;
    }

}

これがstrings.xmlで使用した文字列配列です

<string-array name="my_items">
    <item></item>
    <item>Item 1</item>
    <item>Item 2</item>
</string-array>

次に、OnItemSelectedListener を Spinner に追加します...

mSpinner = (Spinner) mRootView.findViewById(R.id.spinner);
String[] opts = getResources().getStringArray(R.array.my_items);
//DO NOT set the entries in XML OR use an array directly, the adapter will get an immutable List.
List<String> vals = new ArrayList<String>(Arrays.asList(opts));
final EmptyFirstitemAdapter adapter = new EmptyFirstitemAdapter(getActivity(), vals);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    //Track that we have updated after removing the empty item
    private boolean mInitialized = false;
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if(!mInitialized && position == 0 && id == 1){
            // User selected the 1st item after the 'empty' item was initially removed,
            // update the data set to compensate for the removed item.
            mInitialized = true;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Nothing to do
    }
});

「完璧な」解決策ではないかもしれませんが、誰かの役に立てば幸いです。

于 2013-08-30T16:42:17.633 に答える
2

少し考えた後、あなたの目標を達成する方法を思いついたと思います。これには、カスタム アダプターの作成と、スピナーのアイテムが選択されているかどうかを判断するためのフラグの設定/維持が含まれます。この方法を使用すると、偽のデータ (空の文字列) を作成/使用する必要はありません。

基本的に、アダプターgetViewメソッドは閉じたスピナーのテキストを設定します。したがって、それをオーバーライドしてそこに条件を設定すると、起動時に空白のフィールドを作成し、選択後に閉じたスピナー ボックスに表示させることができます。唯一のことは、閉じたスピナーの値を確認する必要があるときはいつでもフラグを設定することを覚えておく必要があるということです。

小さなサンプル プログラムを作成しました (以下のコード)。

この例に必要な単一のコンストラクターのみを追加したことに注意してください。標準の ArrayAdapter コンストラクターをすべて実装することも、必要なコンストラクターのみを実装することもできます。

SpinnerTest.java

public class SpinnerTestActivity extends Activity {
    private String[] planets = { "Mercury", "Venus", "Earth", "Mars",
            "Jupiter", "Saturn", "Uranus", "Neptune" };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        CustomAdapter adapter = new CustomAdapter(this,              // Use our custom adapter
                android.R.layout.simple_spinner_item, planets);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                CustomAdapter.flag = true;                       // Set adapter flag that something
                has been chosen
            }
        });
    }
}

CustomAdapter.java

public class CustomAdapter extends ArrayAdapter {
    private Context context;
    private int textViewResourceId;
    private String[] objects;
    public static boolean flag = false;
    public CustomAdapter(Context context, int textViewResourceId,
            String[] objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.textViewResourceId = textViewResourceId;
        this.objects = objects;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
            convertView = View.inflate(context, textViewResourceId, null);
        if (flag != false) {
            TextView tv = (TextView) convertView;
            tv.setText(objects[position]);
        }
        return convertView;
    }
}
于 2012-07-14T13:47:08.453 に答える
-1

スピナーの最初の要素を空にするかstring、次のように何も選択されていないことを示す必要があります。

String[] ch= {"","Session1", "Session2", "Session3"};

また

String[] ch= {"Nothing selected", "Session1", "Session2", "Session3"};

助けたい

于 2012-07-14T13:09:50.770 に答える