Tạo một bố cục XML đầu tiên trong thư mục res/layout/main.xml
của dự án của bạn:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/addBtn"
android:text="Add New Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
</LinearLayout>
Đây là một bố cục đơn giản với một nút trên đầu và xem danh sách ở phía dưới. Lưu ý rằng ListView
có id @android:id/list
xác định mặc định ListView
một ListActivity
có thể sử dụng.
public class ListViewDemo extends ListActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
}
android.R.layout.simple_list_item_1
là bố cục mục danh sách mặc định do Android cung cấp và bạn có thể sử dụng bố cục cổ phiếu này cho những thứ không phức tạp.
listItems
là Danh sách chứa dữ liệu được hiển thị trong Chế độ xem danh sách. Tất cả việc chèn và xóa phải được thực hiện trên listItems
; các thay đổi trong listItems
phải được phản ánh trong chế độ xem. Đó là xử lý bởi ArrayAdapter<String> adapter
, mà phải được thông báo bằng:
adapter.notifyDataSetChanged();
Một Adapter được khởi tạo với 3 thông số: bối cảnh, mà có thể là activity/listactivity
của bạn; bố cục của mục danh sách cá nhân của bạn; và cuối cùng, danh sách, là dữ liệu thực tế được hiển thị trong danh sách.
Câu trả lời hiện đang cao nhất bình chọn từ Shardul được coi là chất lượng cao và người dùng đã bày tỏ họ cảm thấy nó nên được chấp nhận. Bạn có thể xem xét chấp nhận nó? – Welkie