Android - 在按钮点击时向自定义列表视图中添加项目

4
我目前有一个自定义的列表视图,其中每个列表项包含两行文本。我想要做的是,每当用户点击按钮时,它就会创建一个新的列表项,其中包含用户输入的文本。虽然我知道如何获取文本,但我无法添加新的列表项到列表视图中,因为我不知道从哪里开始。
这是我的代码:
public class MainFeedActivity extends ListActivity implements OnClickListener {
    View sendButton;
    EditText postTextField;
    TextView currentTimeTextView, mainPostTextView;
    ListView feedListView;
    String[] test;
    ArrayList<HashMap<String, String>> list;

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

        //create button and implement on click listener
        sendButton = this.findViewById(R.id.sendPostButton);
        sendButton.setOnClickListener(this);

        list = new ArrayList<HashMap<String, String>>();

        //create the adapter for the list view
        SimpleAdapter adapter = new SimpleAdapter(
            this,
            list,
            R.layout.post_layout,
            new String[]{"time", "post"},
            new int[]{R.id.postTimeTextView, R.id.postTextView});
        //fill the list view with something - TEST
        fillData();
        //set list adapter 
        setListAdapter(adapter);
    }

    public void fillData() {
        //long timeTest = System.currentTimeMillis();
        HashMap<String, String> temp = new HashMap<String, String>();
        temp.put("time", "current time");
        temp.put("post", "USER TEXT GOES HERE");
        list.add(temp);
    }

    @Override
    public void onClick(View button) {
        switch (button.getId()) {
            case R.id.sendPostButton:
                break;
        }
    }
}
2个回答

7

只需要向您的ArrayList中添加一个新元素(就像在fillData中一样),然后调用adapter.notifyDataSetChanged()即可。


1

在调用 fillData() 后,只需调用 adapter.notifyDataSetChanged()

NotifyDataSetChanged() - 通知已附加的视图基础数据已更改,并应刷新自身。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接