Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

使用 listView,但是在通过 adapter将数据存进去时,app 发生闪退?

  1. MainActivity 如下:

package cn.han.listview01;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView lv_music;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

        ListView list1 = (ListView) findViewById(R.id.list1);

        String arr1[] = {"1111111111","222222222222","3333333333"};
        ArrayAdapter adapter1 = new ArrayAdapter<>(this,R.layout.array_item,arr1);
        list1.setAdapter(adapter1);



    }


}

2.app 一进去页面

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cn.han.listview01.MainActivity">

    <ListView
        android:layout_width="368dp"
        android:id="@+id/list1"
        android:entries="@array/books"
        android:divider="#f00"
        android:dividerHeight="2px"
        android:padding="10dp"
        android:layout_height="wrap_content" />



</android.support.constraint.ConstraintLayout>

3.单个item 页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="24dp"
        android:padding="10dp"
        android:shadowColor="#f0f"
        android:shadowDx="4"
        android:shadowDy="4"
        android:shadowRadius="2"
        android:text="TextView" />

</LinearLayout>

现在控制台提示 03-30 16:32:56.357 15648-15648/cn.han.listview01 E/ArrayAdapter: You must supply a resource ID for a TextView,但是我在 adapter 中是添加了 单个item的 xml 布局的嘛,有谁知道这个怎么回事吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

需要指定字符串填充到那个控件,使用这个构造函数

ArrayAdapter (Context context, 
                int resource, 
                int textViewResourceId, 
                List<T> objects)

代码如下:

ArrayAdapter adapter1 = new ArrayAdapter<>(this,R.layout.array_item,R.id.textView,arr1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...