You will need a Adapter
inheriting from BaseAdapter
. This will enable you to% accept% other objects.
For this, you will need to create a Adapter
template that has its Pais
and id
attribute of the country as its attribute and pass to its nome
, and finally set this Adapter
to its Adapter
.
Try something like this:
Country :
public class Pais {
private final int id;
private final String nome;
public Pais(int id, String nome) {
this.id = id;
this.nome = nome;
}
public int getId() {
return id;
}
public String getNome() {
return nome;
}
}
item_pais.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_nome"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MyAdapter :
public class MeuAdapter extends BaseAdapter {
private final List<Pais> paises;
private final LayoutInflater inflater;
MeuAdapter(List<Pais> paises, Context context) {
this.paises = paises;
//LayoutInflater para inflar o seu Layout
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return paises.size();
}
@Override
public Object getItem(int position) {
return paises.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_pais, null);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.tvNome = (TextView) convertView.findViewById(R.id.tv_nome);
}
//Recupeando o seu pais de acordo com a posição
Pais pais = paises.get(position);
//Definindo o texto do item da sua linha
holder.tvNome.setText(pais.getNome());
convertView.setTag(holder);
return convertView;
}
class ViewHolder {
TextView tvNome;
}
}
MainActivity :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Pais> paises = new ArrayList<>();
paises.add(new Pais(0, "Brasil"));
paises.add(new Pais(1, "Argentina"));
paises.add(new Pais(2, "Portugal"));
MeuAdapter meuAdapter = new MeuAdapter(paises, this);
ListView listView = (ListView) findViewById(R.id.sua_list_view);
listView.setAdapter(meuAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Pais pais = (Pais) parent.getAdapter().getItem(position);
//Recuperando o ID do país.
Toast.makeText(MainActivity.this, String.valueOf(pais.getId()), Toast.LENGTH_SHORT).show();
}
});
}
}