我注意到从API 17开始不推荐使用TwoLineListItem。如果我按如下方式设置ListActivity适配器,可以使用哪种替代方法?:
ArrayAdapter<File> adapter = new ArrayAdapter<File>(this,android.R.layout.simple_list_item_2,filesArrayList){
@Override
public View getView(int position, View convertView, ViewGroup parent){
final TwoLineListItem row;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null);
}else{
row = (TwoLineListItem)convertView;
}
row.getText1().setText(filesArrayList.get(position).getTitle());
row.getText2().setText2(filesArrayList.get(position).getDescription());
return row;
}
};
答案 0 :(得分:15)
只需将TwoLineListItem源代码剪切并粘贴到您自己的布局中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/text1"
android:textSize="16sp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/text2"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
(注意我改变了ID以保持一致性。)
现在使用一个ViewHolder来保持对TextViews的引用:
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView == null){
// You should fetch the LayoutInflater once in your constructor
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_2, null);
// Initialize ViewHolder here
}else{
holder = (ViewHolder) convertView.getTag();
}
File file = filesArrayList.get(position);
holder.text1.setText(file.getTitle());
holder.text2.setText2(file.getDescription());
return convertView;
}
答案 1 :(得分:6)
我就这样做了:
mAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_2, mListItems) { @Override public View getView(int position, View convertView, ViewGroup parent) { View row; if(convertView == null) { row = (View)mInflater.inflate(android.R.layout.simple_list_item_2, parent, null); } else { row = (View)convertView; } TextView v = (TextView) row.findViewById(android.R.id.text1); v.setText(mListItems[position]); v = (TextView) row.findViewById(android.R.id.text2); v.setText(mListSubItems[position]); return row; } };
ListView lv = (ListView) getActivity().findViewById(R.id.runsListView);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(mMessageClickedHandler);
答案 2 :(得分:0)
首先是弃用,所以这对你来说并不算太糟糕。因为它将永远得到支持。 ;)
<强> If it ain’t broke, don’t fix it. 强>
您可以自由使用任何布局! 如果您使用模式选择,只需添加一些背景来回复所选状态,例如:
android:background="?android:attr/activatedBackgroundIndicator"