2011-10-17 106 views
4

我目前有一个自定义列表视图,其中列表中的每个项目包含两行文本。我想要做的是每次用户点击按钮时,它会在用户输入的文本列表上创建一个新项目。虽然我知道如何获取文本,但我无法将新项目添加到列表视图,因为我根本不知道从哪里开始。Android - 将项目添加到按钮上的自定义列表视图点击

这里是我的代码:

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

回答

7

这是添加新的元素添加到ArrayList(就像你在做fillData),然后调用adapter.notifyDataSetChanged()一样简单。

1

调用fillData()后,只需拨打adapter.notifyDataSetChanged()即可。

NotifyDataSetChanged() - 通知附加的View,底层数据已被更改,并且应该自行刷新。

相关问题