Listview加載單一的item 布局有時(shí)候不能完全滿足業(yè)務(wù)需求,我們需要加載兩種或兩種以上不同的布局瞒瘸,實(shí)現(xiàn)方法很簡(jiǎn)單:
重寫(xiě) getViewTypeCount() – 返回你加載 不同的布局的個(gè)數(shù)
重寫(xiě) getItemViewType(int) – 根據(jù)position返回view的type id
根據(jù)view item的類型边坤,在getView中創(chuàng)建正確的convertView
代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(new ListviewAdapter());
}
class ListviewAdapter extends BaseAdapter {
@Override
public int getCount() {
return 50;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
int type = getItemViewType(position);
switch (type) {
case 0:
view = LayoutInflater.from(MainActivity.this).inflate(R.layout.listviewitem, parent, false);
TextView tv = (TextView) view.findViewById(R.id.item_tv);
tv.setText("textView" + position);
break;
case 1:
view = LayoutInflater.from(MainActivity.this).inflate(R.layout.listviewpic, parent, false);
break;
}
return view;
}
@Override
public int getViewTypeCount() {
//多少種布局
return 2;
}
@Override
public int getItemViewType(int position) {
return position % 4 == 0 ? 1 : 0;
}
}
}
運(yùn)行效果东涡,每三個(gè)item一個(gè)分隔圖片