填充 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
填充自身。