开发者

Error Binding An ArrayAdapter of strings to a ListVew :( Help

开发者 https://www.devze.com 2023-02-18 08:26 出处:网络
I don\'t know how to bind a ListView to an Array of strings I am pulling out of a resource file.Android.

I don't know how to bind a ListView to an Array of strings I am pulling out of a resource file. Android.

Here is the code I have so far after hours and hours of trying to figure it out. I can't find any clear documentation that really explains to me how to do this. Conceptually, it feels right to me, so maybe I am missing some core Android domain knowledge.

Here is the specific problem in the log:

03-23 02:38:40.169: ERROR/AndroidRuntime(1156): Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

Here is the code I am using:

Main.xml

<ListView android:id="@+id/menuMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
    <TextView android:id="@+id/menuMain_item"  
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    </TextView>
</ListView>开发者_StackOverflow; 

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">App Systems</string>
    <array name="mainMenuItems">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
        <item>Item 4</item>
    </array>
</resources>

main.java

package com.appsystems.appname;

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

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView menuMain = (ListView)findViewById(R.id.menuMain);
        String[] mainMenuItems = getResources().getStringArray(R.array.mainMenuItems);
        ArrayAdapter<String> aa;


        aa = new ArrayAdapter<String>(this, R.id.menuMain_item, mainMenuItems);

        menuMain.setAdapter(aa);
    }
}


In order to create a simple list using ArrayAdapter, you must supply it's constructor a layout containing a single TextView. Remove the TextView inside menuMain and change the arrayAdapter constructor to this:

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


I think in order to use an ArrayAdapter on a ListView I believe your main class needs to extend ListActivity

public class Main extends ListActivity {

I'm also new so I'm not sure. You might try this.

0

精彩评论

暂无评论...
验证码 换一张
取 消