Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a ListView without ListActivity? (use only Activity)

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

like image 660
TIMEX Avatar asked Feb 11 '10 03:02

TIMEX


People also ask

What does ListView uses to place each item?

ListView uses Adapter classes which add the content from data source (such as string array, array, database etc) to ListView.

What is ListView explain it using appropriate examples?

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.


2 Answers

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();       } }); 
like image 134
Patrick Kafka Avatar answered Sep 23 '22 06:09

Patrick Kafka


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);   } } 
like image 34
John Leimon Avatar answered Sep 23 '22 06:09

John Leimon