Android - Add item to custom listview on button click

爷,独闯天下 提交于 2019-12-04 03:56:09

问题


I currently have a custom listview where each item on the list contains two rows of text. What I would like to do is each time a user clicks on the button, it creates a new item on the list with the text that the user inputted. While I know how to get the text, I am having trouble adding a new item to the list view as I simply don't know where to begin.

Here is my code:

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;
        }
    }
}

回答1:


It's as simple as adding a new element to your ArrayList (like you do in fillData), then calling adapter.notifyDataSetChanged().




回答2:


After calling fillData(), just make a call on adapter.notifyDataSetChanged().

NotifyDataSetChanged() - Notifies the attached View that the underlying data has been changed and it should refresh itself.



来源:https://stackoverflow.com/questions/7796456/android-add-item-to-custom-listview-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!