2010-12-27 40 views
274

Có ai có thể giải thích hoặc đề xuất hướng dẫn tạo danh sáchView trong Android không?Tự động thêm các phần tử vào danh sáchXem Android

Dưới đây là yêu cầu của tôi:

  • tôi sẽ có thể tự động thêm các yếu tố mới bằng cách nhấn một nút.
  • nên đủ đơn giản để hiểu (có thể không có bất kỳ cải tiến hiệu suất hoặc convertview, ví dụ)

Tôi biết có khá một vài câu hỏi về chủ đề này, được đăng ở đây trên StackOverflow, nhưng không thể tìm thấy mọi thứ sẽ trả lời câu hỏi của tôi. Cảm ơn!

+0

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

Trả lời

549

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.

+21

dường như anh ấy không hài lòng ;-) – Saqib

+2

Tôi không hiểu cách ListView tự gắn nó vào hoạt động của chúng tôi tại đây. – Breedly

+7

@Breedly Bởi vì nó là một ** ListActivity ** và không phải là một ** Hoạt động trong đó có một bố trí với một ListView **. Bạn không cần tìm chế độ xem của id. Như bạn có thể đọc trên Tham chiếu: 'ListActivity là một hoạt động bao gồm ListView làm phần tử bố cục duy nhất của nó theo mặc định. [...] (nó) lưu trữ một đối tượng ListView'. Vì vậy, theo mặc định các phương thức (như * setAdapter *, vv) là "bên trong" lớp. – Fllo

50

thay vì

listItems.add("New Item"); 
adapter.notifyDataSetChanged(); 

bạn có thể trực tiếp gọi

adapter.add("New Item"); 
+0

sự khác biệt @ venkat530 là gì? Nó là thực hành tốt nhất hay .... một cái gì đó? – gumuruh

+0

@gumuruh bộ điều hợp chính nó là mutable vì vậy chúng tôi có thể trực tiếp thêm hoặc loại bỏ các đối tượng mà sẽ gọi notifyDatasetChanged() và getView() của listView tự động. Điều này làm giảm thêm dòng mã. – venkat530

+0

vì vậy bằng cách thêm vào bộ chuyển đổi tự động gọi notifyDatasetChanged()? Ồ, tôi hiểu rồi. Cảm ơn @ venkat530. Nhưng còn bản thân danh sách thì sao? Tôi có nghĩa là nếu nói trước hết anh ta tạo ra một danh sách array được sử dụng như một thùng chứa dữ liệu cho adapter. Và bây giờ bạn chỉ cần thêm một mục trực tiếp vào bộ điều hợp thay cho danh sách mảng. Dữ liệu danh sách mảng sẽ được cập nhật/bị ảnh hưởng? – gumuruh

39

Trước tiên, bạn cần phải thêm một ListView, một EditText và một nút vào activity_main.xml của bạn.

Bây giờ, trong ActivityMain của bạn:

private EditText editTxt; 
private Button btn; 
private ListView list; 
private ArrayAdapter<String> adapter; 
private ArrayList<String> arrayList; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    editTxt = (EditText) findViewById(R.id.editText); 
    btn = (Button) findViewById(R.id.button); 
    list = (ListView) findViewById(R.id.listView); 
    arrayList = new ArrayList<String>(); 

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown), 
    // and the array that contains the data 
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList); 

    // Here, you set the data in your ListView 
    list.setAdapter(adapter); 

    btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      // this line adds the data of your EditText and puts in your array 
      arrayList.add(editTxt.getText().toString()); 
      // next thing you have to do is check if your adapter has changed 
      adapter.notifyDataSetChanged(); 
     } 
    }); 
} 

này làm việc cho tôi, tôi hy vọng tôi đã giúp bạn

+2

Giải thích rất tốt và cảm ơn đặc biệt để giải thích mục bộ điều hợp - dường như xuất hiện một cách kỳ diệu trong các ví dụ của người khác. :) – raddevus

16

Nếu bạn muốn có ListView trong một AppCompatActivity thay vì ListActivity, bạn có thể làm như sau (Sửa đổi @ câu trả lời Shardul của):

public class ListViewDemoActivity extends AppCompatActivity { 
    //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; 
    private ListView mListView; 

    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.activity_list_view_demo); 

     if (mListView == null) { 
      mListView = (ListView) findViewById(R.id.listDemo); 
     } 

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

    protected ListView getListView() { 
     if (mListView == null) { 
      mListView = (ListView) findViewById(R.id.listDemo); 
     } 
     return mListView; 
    } 

    protected void setListAdapter(ListAdapter adapter) { 
     getListView().setAdapter(adapter); 
    } 

    protected ListAdapter getListAdapter() { 
     ListAdapter adapter = getListView().getAdapter(); 
     if (adapter instanceof HeaderViewListAdapter) { 
      return ((HeaderViewListAdapter)adapter).getWrappedAdapter(); 
     } else { 
      return adapter; 
     } 
    } 
} 

Và trong bạn bố trí thay vì sử dụng android:id="@android:id/list" bạn có thể sử dụng android:id="@+id/listDemo"

Vì vậy, bây giờ bạn có thể có một ListView bên trong một thông thường AppCompatActivity.

5

Mã cho tệp MainActivity.java.

public class MainActivity extends Activity { 

    ListView listview; 
    Button Addbutton; 
    EditText GetValue; 
    String[] ListElements = new String[] { 
     "Android", 
     "PHP" 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     listview = (ListView) findViewById(R.id.listView1); 
     Addbutton = (Button) findViewById(R.id.button1); 
     GetValue = (EditText) findViewById(R.id.editText1); 

     final List <String> ListElementsArrayList = new ArrayList <String> 
      (Arrays.asList(ListElements)); 


     final ArrayAdapter <String> adapter = new ArrayAdapter <String> 
      (MainActivity.this, android.R.layout.simple_list_item_1, 
       ListElementsArrayList); 

     listview.setAdapter(adapter); 

     Addbutton.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       ListElementsArrayList.add(GetValue.getText().toString()); 
       adapter.notifyDataSetChanged(); 
      } 
     }); 
    } 
} 

Mã cho activity_main.xml file layout.

<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" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.listviewaddelementsdynamically_android_examples 
    .com.MainActivity" > 

    <Button 
    android:id="@+id/button1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/editText1" 
    android:layout_centerHorizontal="true" 
    android:text="ADD Values to listview" /> 

    <EditText 
    android:id="@+id/editText1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="26dp" 
    android:ems="10" 
    android:hint="Add elements listView" /> 

    <ListView 
    android:id="@+id/listView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/button1" 
    android:layout_centerHorizontal="true" > 
    </ListView> 

</RelativeLayout> 

screenshot

enter image description here

Các vấn đề liên quan