[英]How to add ListView items on button click using adapter
如何獲取在EditText中輸入的數據並在該窗口中單擊“提交”應該將其添加到以前的活動列表視圖項? 我需要做的是:
我在這里看到了類似的問題: 向listview動態添加項目android
但我無法理解答案。有人請解釋如何做到這一點。
您只需執行以下操作:准備您的xml,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/addItem"
android:hint="Add a new item to List View" />
<Button
android:id="@+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Add" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText" >
</ListView>
</RelativeLayout>
活動如下:
public class MainActivity extends Activity {
EditText editText;
Button addButton;
ListView listView;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.addItem);
listView = (ListView) findViewById(R.id.listView);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
}
創建String Arraylist
並初始化它
ArrayList<String> str1 = new ArrayList<String>();
在其上添加一些值
str1.add("First Row");
str1.add("Second Row");
str1.add("Third Row");
str1.add("Fourth Row");
str1.add("Fifth Row");
然后將Adapter
設置為ListView
adapter=new ListAdapter(this,str1);
list.setAdapter(adapter);
然后將您的EditText
文本添加到str1中,然后調用adapter.notifyDataSetChanged();
喜歡
str1.add(edit_message.getText().toString());
adapter.notifyDataSetChanged();
嘗試將此代碼添加到Button onclick()
演示輸出:
假設你有一個arraylist
ArrayList<String> dataList = new Arraylist ();
因此, On clicking of button, you need to add the new data item into your data arraylist.
首先,在edittext中輸入值並存儲在字符串中。
String editedValue = yourEditText.getText.toString();
然后我們需要在我們的datalist中添加它。
喜歡
dataList.add(editedValue);
然后只需調用adapter.notifyDataSetChanged()
yourAdapter.notifyDataSetChanged();
它會工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.