谁能给我提供 two_line_list_item 的例子?
问问题
24685 次
1 回答
37
我还没有找到一个实际使用内置布局的示例,android.R.layout.two_line_list_item
以及一个ListView
insted 的ListActivity
. 所以这里。
如果您赶时间,下面的覆盖是使用默认布局TwoLineArrayAdapter.getView()
的重要部分。two_line_list_item
您的数据
您有一个定义列表项的类。我假设你有一个数组。
public class Employee {
public String name;
public String title;
}
一个抽象的 TwoLineArrayAdapter
这个抽象类可以重用,并且使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);
}
一个具体的 TwoLineArrayAdapter
最后,这是您编写的特定于 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;
}
}
活动.onCreate()
在您的 ActivityonCreate()
方法中,您将拥有如下所示的代码:
employees = new Employee[...];
//...populate the employee array...
employeeLV = (ListView)findViewById(R.id.employee_list);
employeeLV.setAdapter(new EmployeeArrayAdapter(this, employees);
于 2012-03-21T22:57:20.087 回答