簡體   English   中英

Android - 點擊按鈕,將項目添加到自定義列表視圖

[英]Android - Add item to custom listview on button click

我目前有一個自定義列表視圖,其中列表中的每個項目包含兩行文本。 我想要做的是每次用戶點擊按鈕時,它會在列表中創建一個新項目,其中包含用戶輸入的文本。 雖然我知道如何獲取文本,但我無法在列表視圖中添加新項目,因為我根本不知道從哪里開始。

這是我的代碼:

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

它就像向ArrayList添加一個新元素一樣簡單(就像你在fillDatafillData ),然后調用adapter.notifyDataSetChanged()

在調用fillData()之后,只需在adapter.notifyDataSetChanged()上調用。

NotifyDataSetChanged () - 通知附加的View基礎數據已更改,並且應自行刷新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM