有人能为我提供two_line_list_item的示例吗?
有人能为我提供two_line_list_item的示例吗?
我尚未找到一个实际使用内置布局android.R.layout.two_line_list_item
和ListView
而不是ListActivity
的示例。所以现在开始。
如果你很匆忙,下面的TwoLineArrayAdapter.getView()
重写是使用默认的two_line_list_item
布局的重要部分。
你有一个定义列表项的类。我假设你有一个这些类的数组。
public class Employee {
public String name;
public String title;
}
这个抽象类可以被重复使用,使得定义一个两行 ListView
更加容易。你可以提供自己的布局,但是两个参数的构造函数使用内置的 two_line_list_item
布局。 自定义列表项布局的唯一要求是它们必须使用 @android:id/text1
和 @android:id/text2
来标识它们的 TextView
子项,就像 two_line_list_item
一样。
public abstract class TwoLineArrayAdapter<T> extends ArrayAdapter<T> {
private int mListItemLayoutResId;
public TwoLineArrayAdapter(Context context, T[] ts) {
this(context, android.R.layout.two_line_list_item, ts);
}
public TwoLineArrayAdapter(
Context context,
int listItemLayoutResourceId,
T[] ts) {
super(context, listItemLayoutResourceId, ts);
mListItemLayoutResId = listItemLayoutResourceId;
}
@Override
public android.view.View getView(
int position,
View convertView,
ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listItemView = convertView;
if (null == convertView) {
listItemView = inflater.inflate(
mListItemLayoutResId,
parent,
false);
}
// The ListItemLayout must use the standard text item IDs.
TextView lineOneView = (TextView)listItemView.findViewById(
android.R.id.text1);
TextView lineTwoView = (TextView)listItemView.findViewById(
android.R.id.text2);
T t = (T)getItem(position);
lineOneView.setText(lineOneText(t));
lineTwoView.setText(lineTwoText(t));
return listItemView;
}
public abstract String lineOneText(T t);
public abstract String lineTwoText(T t);
}
最后,这是你根据你的Employee类编写的代码,以便在你的ListView
中呈现。
public class EmployeeArrayAdapter extends TwoLineArrayAdapter<Employee> {
public EmployeeArrayAdapter(Context context, Employee[] employees) {
super(context, employees);
}
@Override
public String lineOneText(Employee e) {
return e.name;
}
@Override
public String lineTwoText(Employee e) {
return e.title;
}
}
在你的活动(Activity)的 onCreate()
方法中,你将会有类似以下代码:
employees = new Employee[...];
//...populate the employee array...
employeeLV = (ListView)findViewById(R.id.employee_list);
employeeLV.setAdapter(new EmployeeArrayAdapter(this, employees);