Android自定义ListView无法正常工作

时间:2014-06-02 16:05:04

标签: android android-listview android-arrayadapter

我正在尝试使用ArrayAdapter创建自定义列表视图,每行显示一个Image& TextView中。我使用以下代码,但应用程序无法运行:

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是映射到MainActivity的布局文件。但是,我在分配适配器时使用custom_layout.xml文件来自定义布局。请有人告诉我我做错了什么?提前谢谢。

3 个答案:

答案 0 :(得分:3)

对于使用Android ListActivity,您的ListView应具有ID

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

请参阅Link

答案 1 :(得分:2)

缺少

setContentView(R.layout.activity_main);

进入onCreate方法

 @Override
 public void onCreate(Bundle savedInstanceState) {

        super.onCreate (savedInstanceState);   
        setContentView(R.layout.activity_main);     
        setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout, R.id.txtName, buzzWords));
 }

还有..

进入activity_main.xml@+id/android:list替换为@android:id/list

答案 2 :(得分:0)

将自定义布局更改为
customlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:textSize="30sp" >
</TextView>

并改变这个

 setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout, R.id.txtName, buzzWords));
OnCreate方法

 setListAdapter (new ArrayAdapter<String>(this, R.layout.customlayout,buzzWords));