Error in simple android app list adapter

时间:2016-05-11 11:36:40

标签: java android android-layout

This is my java code:

import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
ListView myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myList=(ListView)findViewById(R.id.myList);
    List<String> array_list=new ArrayList<String>();
    array_list.add("One Option");
    array_list.add("Two Option");
    array_list.add("Three Option");
    ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.activity_main,array_list);
    myList.setAdapter(arrayAdapter);

}

}

and this is my xml layout:

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

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/myList"
    android:drawSelectorOnTop="false" />

When I run my app i get this error

Application Stoppes

and this is what is in android monitor in case that you may need:

Android Monitor Screen

This is what I have done so far.

enter image description here

4 个答案:

答案 0 :(得分:2)

在这里做错了

ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.activity_main,array_list);

你正在通过R.layout.activity_main。设置R.layout.list_item_layout

答案 1 :(得分:1)

请参阅此内容。

您只需执行此操作android.R.layout.simple_list_item_1

 ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array_list);

编辑1

  

什么是simple_list_item_1?

它是对 Android OS 的内置XML布局文档的引用,而不是您自己的XML布局之一。

Refer this.

答案 2 :(得分:1)

试试这个

     ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,array_list);
myList.setAdapter(arrayAdapter);

答案 3 :(得分:1)

你需要通过,

android.R.layout.simple_list_item_1

android.R.layout.simple_spinner_item

android.R.layout.simple_dropdown_item_1line

等...

这可能对你有所帮助。