我有一个带有 OnClick 方法的 ListView,我想更改单击的 ListViewItem 的布局。我想通过将布局设置为新的 XML 来做到这一点。当视图加载时,我在 ArrayAdapter 的 getView 方法中设置项目的默认布局
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(position % 2 == 0){
v = vi.inflate(R.layout.wizard_listview_rowlayout_even, null);
} else {
v = vi.inflate(R.layout.wizard_listview_rowlayout_odd, null);
}
这有效,因为该方法返回膨胀的视图。我尝试在 onClick 方法中使用它
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.wizard_listview_rowlayout_checked, null);
但这不起作用,可能是因为 View (v) 永远不会返回。有什么方法可以操作视图(ListViewItem)以更新应用程序中的布局?
我试过使用选择器,但它只会让我的应用程序崩溃,而且我觉得使用这种方法我已经很接近了。
谢谢 :)
编辑:这是我完整的 ListViewFiller 类:
public class ListViewFiller extends ListActivity {
private Context context;
private ArrayList<String> items;
private final ListView listview;
ListViewFiller(final ListView listview, ArrayList<String> items, Context appContext){
context = appContext;
this.listview = listview;
this.items = items;
ArrayAdapter adapter = new StudiesAdapter(appContext, android.R.layout.simple_list_item_1, items);
listview.setAdapter(adapter);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
v.setSelected(true);
print();
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.wizard_listview_rowlayout_checked, null);
listview.invalidate();
}
});
}
public class StudiesAdapter extends ArrayAdapter<String> {
private ArrayList<String> studies;
public StudiesAdapter(Context context, int textViewResourceId, ArrayList<String> studies) {
super(context, textViewResourceId, studies);
this.studies = studies;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (true) { //opprinnelig if(v == null)
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(position % 2 == 0){
v = vi.inflate(R.layout.wizard_listview_rowlayout_even, null);
} else {
v = vi.inflate(R.layout.wizard_listview_rowlayout_odd, null);
}
}
String study = studies.get(position);
if (study != null) {
TextView text = (TextView) v.findViewById(R.id.label);
if (text != null) {
text.setText(study);
Typeface face = Typeface.createFromAsset(context.getAssets(), "MyriadWebPro-Bold.ttf");
text.setTypeface(face);
}
}
return v;
}
}
}
我试图实现的是当单击列表项(并调用 onItemClick 方法)时,我想将项目的布局设置为 xml 文件“R.layout.wizard_listview_rowlayout_checked”。