我已经尝试了一段时间,但我似乎仍然无法做到正确。我可以将自定义标头添加到列表视图,但我无法将自定义行布局添加到列表中。我希望列表中的每一行都有文件“listitemrow.xml”的布局,但我似乎不太明白如何做到这一点,尽管阅读了多个教程。
这是我的代码
public class PortfolioFragMent extends android.app.ListFragment{
private String[] ShareholdingNames;
private ListView mainListView ;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ListView listView = new ListView(getActivity());
super.onCreate(savedInstanceState);
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.listviewheader, listView, false);
listView.addHeaderView(header, null, false);
ViewGroup listrow = (ViewGroup)inflater.inflate(R.layout.listitemrow, listView, false);
//listView.add(listitemrow); I want to do something like this
ArrayAdapter<String> array = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1);
setListAdapter(array);
ShareholdingNames= ShareholdingNames();
for (String str : ShareholdingNames)
array.add(str);
listView.setAdapter(array);
return listView;
}
private String[] ShareholdingNames(){
ShareholdingNames = new String[Portfolio.getPortfolio().count()];
for(int i=0; i < Portfolio.getPortfolio().count(); i++){
ShareholdingNames[i]= Portfolio.getPortfolio().getShareHolding(i).getName();
}
return ShareholdingNames;
}
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailShareHoldingActivity.class);
intent.putExtra("new_variable_name","value");
intent.putExtra("bookPositionInList",position);
startActivity(intent);
}
}
答案 0 :(得分:4)
为此,您需要添加自己的自定义适配器并添加行
ViewGroup listrow = (ViewGroup)inflater.inflate(R.layout.listitemrow, listView, false);
进入适配器的getView
方法..
public class ListAdapter extends ArrayAdapter<Item> {
public ListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.listitemrow, listView, false);
}
...
return v;
}
}