Search code examples
androidandroid-listviewandroid-arrayadapter

Android custom ListView not working


I am trying to create a custom listview using an ArrayAdapter with each row displaying an Image & TextView. I am using the following code but the application fails to run:

MainActivity.java

package demo.android.listviewadapter;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
    
    String[]     buzzWords = {"Buzz-1", "Buzz-2", "Buzz-3", "Buzz-4", "Buzz-5", "Buzz-6", "Buzz-7"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        
        super.onCreate (savedInstanceState);        
        setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout, R.id.txtName, buzzWords));
    }
    
    @Override
    public void onListItemClick (ListView parent, View v, int position, long id) {
        
        Toast.makeText(this, "You Clicked: " + buzzWords [position], Toast.LENGTH_SHORT).show();
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

customlayout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgName"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/txtName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@+id/txtName"
         />

</LinearLayout>

activity_main.xml is the layout file which maps to the MainActivity. However, I use the custom_layout.xml file to customize the layout when assigning the adapter. Please can someone tell what am I doing wrong? Thanks in advance.


Solution

  • For using android ListActivity your ListView should have the id

    android:id="@android:id/list"
    

    Please refer Link