Let's say i have a list of cities from a country. If the user clicks one of them, i want a new screen to be displayed, with the detailed infos for that list element. Also, that screen will have others buttons ( eg: Write Review, Post Picture )
How can i achieve this ?
This article explains how to search for Item in a ListView. First, you will create an XML file and use an EditText and ListView. The EditText is used to search for an item and the ListView is used to show the list of items. Now you will create a Java file and write code to show an item in a ListView.
Android ListView is a view which contains the group of items and displays in a scrollable list. ListView is implemented by importing android. widget.
Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result.
The City
class should implement Parcelable
. Its toString()
method should return the name of the city. (Rather than simply having the city as a String
.)
When you populate your ListView, use an ArrayAdapter<City>
instead of an ArrayAdapter<String>
(this code assumes that the cities are kept in List<City> list
):
City[] cities = new City[list.size()];
list.toArray(cities);
mListView = (ListView) findViewById(R.id.citylist);
mListView.setAdapter(new ArrayAdapter<City>(this,
R.layout.listitem, cities));
In your onItemClick handler, get the selected city and add it as an extra on the intent you use to launch your details activity:
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a,
View v, int position, long id) {
City city = (City) a.getItemAtPosition(position);
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
intent.putExtra("com.example.cities.City", city);
startActivity(intent);
}
});
In your details activity, get the city from the extras on the intent:
Bundle bundle = getIntent().getExtras();
City city = bundle.getParcelable("com.example.cities.City");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With