I'm new to Android, and I really need to do it this way (I've considered doing it in another Activity), but can anyone show me a simple code (just the onCreate() method) that can do Listview without ListActivity?
THanks
ListView uses Adapter classes which add the content from data source (such as string array, array, database etc) to ListView.
ListView is a subclass of AdapterView and it can be populated by binding to an Adapter, which retrieves the data from an external source and creates a View that represents each data entry. In android commonly used adapters are: Array Adapter.
If you have an xml layout for the activity including a listView like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="fill_parent" Then in your onCreate you could have something like this
setContentView(R.layout.the_view); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, myList); ListView lv = (ListView)findViewById(android.R.id.list); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v,int position, long id) { Toast.makeText(getBaseContext(), "Click", Toast.LENGTH_LONG).show(); } });
Include the following resource in your res/layout/main.xml file:
<ListView android:id="@+id/id_list_view" android:layout_width="fill_parent" android:layout_height="fill_parent" /> your_class.java
import android.widget.ListView; import android.widget.ArrayAdapter; public class your_class extends Activity { private ListView m_listview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); m_listview = (ListView) findViewById(R.id.id_list_view); String[] items = new String[] {"Item 1", "Item 2", "Item 3"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); m_listview.setAdapter(adapter); } }
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