以编程方式在自定义列表视图中添加/删除项目?

时间:2015-02-02 19:14:00

标签: java android listview android-arrayadapter custom-lists

我正在创建一个能够添加或删除项目的自定义列表视图。我尝试使用此代码将新行项添加到列表视图,但它说“方法add(String)未定义为ListView类型”。

这是我的代码:

public class AddActivityCustomList extends ArrayAdapter<String> {

    private final Activity context;
    private final String[] web;

    public AddActivityCustomList(Activity context, String[] web) {
        super(context, R.layout.add_activity_single_list, web);
        this.context = context;
        this.web = web;

    }

    public View getView(final int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.add_activity_single_list,
                null, true);
        TextView txtTitle = (TextView) rowView
                .findViewById(R.id.act_title_single);

        txtTitle.setTypeface(myface);
        txtTitle.setText(web[position]);

        return rowView;

    }

我的添加按钮代码是这样的:

add_activity.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                lv.add(add_act_title.getText().toString());
                add_act_title.setText("");
                adapter.notifyDataSetChanged();
                add_act_title.getText();
            }
        });

lv.add(...部分有问题。我该怎么办?

4 个答案:

答案 0 :(得分:1)

listview显示适配器的数据。通过它的添加功能将新字符串添加到适配器。

答案 1 :(得分:1)

    add_activity.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get the adapter from the listview
            AddActivityCustomList adapter = (AddActivityCustomList) lv.getAdapter();
            // call ArrayAdapter.add, no need to call notifyDataSetChanged as add does this
            adapter.add(add_act_title.getText().toString());
            // clear old title
            add_act_title.setText("");
        }
    });

答案 2 :(得分:0)

您无法将数据直接添加到列表视图中。您需要在适配器中添加数据并调用notifyDataSetChanged()

使用此

@Override
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    adapter.add(add_act_title.getText().toString());
    adapter.notifyDataSetChanged();
    add_act_title.setText("");
    add_act_title.getText();
}

答案 3 :(得分:0)

  

“类型ListView”

的方法add(String)未定义

因为您在ListView而不是Adapter上调用add方法。

  

如何将新行项添加到列表视图

要从ListView添加/删除项目,请使用ArrayList作为数据源而不是Array,因为如果您使用Array并调用适配器add方法,那么您将获得{ {1}}。

所以在UnsupportedOperationException适配器中进行以下更改:

1。使用AddActivityCustomList代替ArrayList<String>数组。

2. 将新项目添加到适配器:

String[]