如何动态创建ListMenu?

时间:2012-02-28 20:59:20

标签: android listactivity listadapter expandablelistadapter

我正在创建一个字典,我正在尝试动态创建ListMenu,因为它是按字母顺序从数据库中过滤单词时自动创建的。 我手动创建了ListMenu,但无法将其转换为动态ListMenu。有没有人知道如何动态创建ListMenu?

这是我的代码:

 package ge.gtug;

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

public class Settings extends ListActivity{


String listItems[] = {"AboutUs", "AboutApp", "Feedback"};
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(Settings.this, android.R.layout.simple_list_item_1, listItems));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    String koba = listItems[position];
    super.onListItemClick(l, v, position, id);
    try{
    Class myClass1 = Class.forName("ge.gtug." + koba);
    Intent myIntent1 = new Intent(Settings.this, myClass1);
    startActivity(myIntent1);
    }catch(ClassNotFoundException e){
        e.printStackTrace();

    try {
    Class myClass2 = Class.forName("ge.gtug." + koba);
    Intent myIntent2 = new Intent(Settings.this, myClass2);
    startActivity(myIntent2);
    }catch(ClassNotFoundException o){
        o.printStackTrace();
            }
    }
}

}

1 个答案:

答案 0 :(得分:0)

使用List(ArrayList,Vector或类似代码)而不是使用Array来存储数据。每当您更改数据收集时,您需要通知ArrayAdapter数据已更改 - 通知数组适配器列表已更改您调用方法

ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Settings.this, android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);

listItems.add("new string");
adapter.notifyDataSetChanged();

http://developer.android.com/reference/android/widget/ArrayAdapter.html#notifyDataSetChanged%28%29