如果您使用的是 ListView,那么拥有一个用于行的 XML 文件非常简单。您唯一需要的是一个 XML 文件和一个 Adapter 类。看看这个简单的例子:
要从数据库中读取数据,请创建一个这样的辅助类:
public class MessagingDatabaseAdapter {
protected SQLiteDatabase database;
public MessagingDatabaseAdapter(Context context) {
MessagingDatabaseHelper databaseHelper = new MessagingDatabaseHelper(context, "message_history_db");
database = databaseHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public void Entity[] getAllEntities() {
Entity[] values = null;
String query = "select * from TABLE_NAME";
Cursor cursor = null;
try {
cursor = database.rawQuery(query, null);
if( cursor.moveToFirst() ) {
int s = cursor.getCount();
values = new Entity[s];
do {
Entity entity = new Entity();
entity.setSomeProperty(cursor.getInt(cursor.getColumnIndex(SOME_PROPERTY_COLUMN)));
values[i++] = entity;
} while( cursor.moveToNext() );
}
} catch(Exception ex) {
} finally {
if( cursor != null ) {
cursor.close();
}
return values;
}
}
protected class MessagingDatabaseHelper extends SQLiteOpenHelper {
public MessagingDatabaseHelper(Context context, String name) {
super(context, name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Your SQL to create Tables");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
在您的活动课程中:
MessagingDatabaseAdapter db = new MessagingDatabaseAdapter();
values = db.getAllEntities();
db.close();
list_view = (ListView) findViewById(R.id.list_view);
ListAdapter adapter = new ListAdapter(this, values);
list_view.setAdapter(adapter);
和 ListAdapter 类:
public class ListAdapter extends ArrayAdapter<Entity> {
final Context context;
final Entity[] values;
public ListAdapter(Context context, Entity[] values) {
super(context, R.layout.list_screen, values);
this.values = values;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_view_item, parent, false);
TextView datetimeTextView = (TextView) rowView.findViewById(R.id.list_view_datetime_text_view);
datetimeTextView.setTypeface(someTypeFace);
return rowView;
}
}
和行布局 XML 文件 (list_view_item.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/BorderedFrame" >
<TextView
android:id="@+id/inbox_list_view_datetime_text_view"
style="@style/MediumText"
android:layout_width="wrap_content" >
</TextView>
</RelativeLayout>