あなたはあなたのためのIDとドロップダウン項目を開催しますスピナーアダプタを使用してカスタムオブジェクトを使用することができます。例えばのために:あなたはデータArrayList
をスピンナーで、このアダプタクラスを使用することができます
public class PlanetData {
int id;
String planetName;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setPlanetName(String planetName) {
this.planetName = planetName;
}
public String getPlanetName() {
return planetName;
}
// We will use this method to get the expand collapse string value of spinner.
@Override
public String toString() {
return planetName;
}
}
:
これは、カスタムクラスは次のようになります方法です。
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.v4.content.res.ResourcesCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* <p>
* Created by Angad Singh on 6/11/17.
* </p>
*/
public class TransactionSpinnerAdapter<T> extends ArrayAdapter<T> {
private Context context;
private List<T> objects;
public TransactionSpinnerAdapter(@NonNull Context context, int resource, @NonNull List<T> objects) {
super(context, resource, objects);
this.context = context;
this.objects = objects;
}
@NonNull
public TextView getView(int position, View convertView, @NonNull ViewGroup parent) {
TextView v = (TextView) super.getView(position, convertView, parent);
v.setText(objects.get(position).toString());
return v;
}
public TextView getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
TextView v = (TextView) super.getView(position, convertView, parent);
v.setText(objects.get(position).toString());
return v;
}
}
あなたActivity
/Fragment
クラスでは、ちょうどあなたがRecyclerView
/ListView
で使用するのと同じ方法でArrayList
を使用しています。
// List of Planets
ArrayList<PlanetData> planets = new ArrayList<>();
//...
//...
PlanetData planet1 = new PlanetData();
planet1.setId(1);
planet1.setPlanetName("Mercury");
//...
//... Create rest of your planets similarly.
//...
planets.add(planet1);
とあなたのOnItemSelectedListener
のコールバックの内側だけで、リストの位置から、惑星のIDを取得します。
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int id = planets.get(pos).getId();
}
アレイの位置を使用する。または同じインデックスの別の配列にidを保存することができます –
配列定義には 'id = n'のようなものはありません。あなたがリンクしたページを再度読んでください。 –