填充 ListView

假設你已經在 Android Studio 中設定了應用程式,請將 ListView 新增到佈局中(如果已經完成,則跳過):

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<!-- Your toolbar, etc -->

<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</android.support.design.widget.CoordinatorLayout>

現在讓我們為我們將要填充我們的 ListView 的資料建立一個模型:

public class Person {

    private String name

    public Person() {
        // Constructor required for Firebase Database
    }

    public String getName() {
        return name;
    }

}

確保你的 ListView 有一個 id,然後在你的 Activity 中建立一個引用並將它的介面卡設定為一個新的 FirebaseListAdapter

public class MainActivity extends AppCompatActivity {

    // ...

    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        // Find the ListView
        mListView = (ListView) findViewById(R.id.list_view);
    
        /* 
         * Create a DatabaseReference to the data; works with standard DatabaseReference methods
         * like limitToLast() and etc.
         */
        DatabaseReference peopleReference = FirebaseDatabase.getInstance().getReference()
            .child("people");

        // Now set the adapter with a given layout
        mListView.setAdapter(new FirebaseListAdapter<Person>(this, Person.class,
                android.R.layout.one_line_list_item, peopleReference) {

            // Populate view as needed
            @Override
            protected void populateView(View view, Person person, int position) {
                ((TextView) view.findViewById(android.R.id.text1)).setText(person.getName());
            }
        });
    }
}

完成後,將一些資料新增到資料庫並觀察 ListView 填充自身。