2011-10-17 12 views
4

現在、リストの各アイテムに2行のテキストが含まれているカスタムリストビューがあります。私がしたいのは、ユーザーがボタンをクリックするたびに、ユーザーが入力したテキストでリストに新しい項目を作成することです。テキストを取得する方法はわかっていますが、どこから始めればいいのか分からないので、リストビューに新しい項目を追加するのは難しいです。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

それは(あなたがfillDataで行うように)ArrayList、その後、adapter.notifyDataSetChanged()を呼び出して、あなたに新しい要素を追加するのと同じくらい簡単です:

は、ここに私のコードです。

1

fillData()を呼び出した後、adapter.notifyDataSetChanged()を呼び出してください。

NotifyDataSetChanged() - 添付されたビューに、基礎となるデータが変更され、自身を更新する必要があることを通知します。

関連する問題