2017-01-11 3 views
0

コードは次のとおりです。どのようにオブジェクトをアンドロイドのスピナーに渡すことができますか?

public class Organization { 

private String name; 
private Long id; 

public Organization(){ 
} 

public Organization(String name, Long id) { 
    super(); 
    this.name = name; 
    this.id = id; 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public Long getId() { 
    return id; 
} 

public void setId(Long id) { 
    this.id = id; 
} 
} 

スピナーは次のとおりです。

Spinner sp = (Spinner) navigationView.getMenu().findItem(R.id.brand_spinner).getActionView(); 
sp.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,contactList)); 
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
     @Override 
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

      String value = parent.getItemAtPosition(position).toString(); 
      Toast.makeText(parent.getContext(),""+value+"",Toast.LENGTH_SHORT).show(); 
     } 
}); 

で名前を選択することで、私はスピナーに両方の名前とidを渡すことができますし、スピナーにリストする必要がありますどのようにスピナー。名前のidをローカル変数に格納します。

+0

http://stackoverflow.com/questions/1625249/android-how-to-bind-spinner-to-custom-object-list –

+0

カスタムアダプタが必要です

このため。 –

+0

http://stackoverflow.com/questions/35983176/how-to-create-spinner-list-using-customadapter-in-android –

答えて

0

BaseAdapterまたはArrayAdapterに拡張され、OrganizationArrayList<>を渡すという独自のカスタムアダプタクラスを作成する必要があります。あなたがcontactListのオブジェクトにcontactList、オーバーライドtoString()を送信しているArrayAdapterについて

ただ、アダプタ

Check Link

0

を作成する際に、それはあなたを助けるこのリンクを確認してください。だからArrayAdapterは、textListにテキストを表示するためにcontactListの各オブジェクトをtoString()メソッドを呼び出してレンダリングします。だから今の項目ののonClick、

sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
     @Override 
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 

      Object obj= parent.getItemAtPosition(position); 
      Contact c = (Contact) obj; 
      System.out.println("id = " + c.getId() + " , Name = " + c.getName()); 

} 
関連する問題