我想显示国家/地区列表(仅限姓名),但我不知道如何。所以我有很长的国家列表,其中包含附加信息,我只想在列表中显示国家/地区的名称。
MainActivity:
listView = (ListView) findViewById(R.id.list_view);
textView = (TextView) findViewById(R.id.text_view);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ICountryService.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
.build();
ICountryService service = retrofit.create(ICountryService.class);
Call<List<Country>> call = service.getCountry();
call.enqueue(new Callback<List<Country>>() {
@Override
public void onResponse(Response<List<Country>> response, Retrofit retrofit) {
if (response.isSuccess()) {
List<Country> countryList = response.body();
ArrayAdapter<Country> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, countryList);
listView.setAdapter(adapter);
} else {
Toast.makeText(MainActivity.this, "Error: " + response.code(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
界面:
public interface ICountryService {
String ENDPOINT = "https://restcountries.eu";
@GET("/rest/v1/all")
Call<List<Country>> getCountry();
}
Country calss太长而无法显示,但我只会粘贴我要调用的元素部分。
public class Country {
/**
*
* (Required)
*
*/
@SerializedName("name")
@Expose
private String name;