0

我创建了这个简单的 android 活动来演示我的问题。

我只希望屏幕有一个 textInput 和一个按钮。在这两个下面,如果按下按钮,我想创建一个ListView(按钮基本上调用了一些方法并获取一个String数组。我希望ListView显示这个数组。

所以它是一个普通的屏幕、一个按钮、一个文本输入,当按下按钮时它会调用一个方法并接收一个字符串数组并希望在它们下面打印列表。

public class TagListViewer  extends ListActivity {

    private Button clickBtn;
    EditText textInput;
    String[] resultStr = {"a", "b", "c"}; //Ideally would want this inside the button OnClickListener... but couldn't bcz I needed one for the Array adapter.

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.tagselection);

        clickBtn = (Button) findViewById(R.id.CreatePL);
        clickBtn.setText("Search");
        textInput = (EditText) findViewById(R.id.textInput);

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

        clickBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();

                adapter.add("ABC"); //This I could use the array I get to add its elements
                adapter.notifyDataSetChanged();
            }

        });
    }
}
4

1 回答 1

2

我不确定您的问题是什么,但我注意到您正在尝试将项目添加到原始字符串数组并创建两个不同的适配器......我对这个问题有预感。看看下面的简单变化:

public class TagListViewer  extends ListActivity {
    // Make adapter a class variable
    private ArrayAdapter<String> adapter;

    private Button clickBtn;
    EditText textInput;

    // You cannot add items to a primitive String array, we'll convert this to an ArrayList
    String[] resultStr = {"a", "b", "c"}; 
    List<String> list = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tagselection);

        // Add contents of resultStr to the dynamic List
        Collections.addAll(list, resultStr);

        clickBtn = (Button) findViewById(R.id.CreatePL);
        clickBtn.setText("Search");
        textInput = (EditText) findViewById(R.id.textInput);

        // Reflect class variable change and use list instead of resultStr
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list);
        setListAdapter(adapter);

        clickBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // This will add the one phrase "ABC"
                //adapter.add("ABC");

                // This will add the contents of textInput
                adapter.add(textInput.getText().toString());
            }
        });
    }
}

从评论中添加

ListActivity 需要android.R.id.list在其布局中有一个带有 id 的 ListView:

<ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
于 2012-08-13T21:05:20.907 回答