Android-单击按钮将项目添加到自定义列表视图
我目前有一个自定义列表视图,其中列表中的每个项目都包含两行文本。我想做的是,每次用户单击按钮时,它都会在列表中创建一个新项目,其中包含用户输入的文本。虽然我知道如何获取文本,但在向列表视图添加新项时遇到了问题,因为我根本不知道从何开始 这是我的密码:Android-单击按钮将项目添加到自定义列表视图,android,listview,buttonclick,Android,Listview,Buttonclick,我目前有一个自定义列表视图,其中列表中的每个项目都包含两行文本。我想做的是,每次用户单击按钮时,它都会在列表中创建一个新项目,其中包含用户输入的文本。虽然我知道如何获取文本,但在向列表视图添加新项时遇到了问题,因为我根本不知道从何开始 这是我的密码: public class MainFeedActivity extends ListActivity implements OnClickListener { View sendButton; EditText postTextFi
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;
}
}
}
公共类MainFeedActivity扩展ListActivity实现OnClickListener{
查看发送按钮;
编辑文本postTextField;
TextView currentTimeTextView、mainPostTextView;
ListView-feedListView;
字符串[]测试;
数组列表;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_提要);
//创建按钮并在单击时实现侦听器
sendButton=this.findviewbyd(R.id.sendPostButton);
sendButton.setOnClickListener(此);
列表=新的ArrayList();
//为列表视图创建适配器
SimpleAdapter适配器=新SimpleAdapter(
这
列表
R.layout.post_布局,
新字符串[]{“时间”,“发布”},
新的int[]{R.id.postTimeTextView,R.id.postTextView});
//用某物填充列表视图-测试
fillData();
//设置列表适配器
setListAdapter(适配器);
}
公共数据(){
//长时间测试=System.currentTimeMillis();
HashMap temp=新的HashMap();
临时投入(“时间”、“当前时间”);
临时放置(“post”,“用户文本在此显示”);
列表。添加(临时);
}
@凌驾
公共void onClick(查看按钮){
开关(button.getId()){
案例R.id.sendPostButton:
打破
}
}
}
只需在数组列表中添加新元素(就像在fillData
中所做的那样),然后调用适配器.notifyDataSetChanged()
调用fillData()后,只需调用适配器.notifyDataSetChanged()
()-通知附加视图基础数据已更改,它应刷新自身