ListView加载两种以上不同的布局
不同的项目布局(item layout)
Listview一种单一的item 布局有时候不能完全满足业务需求,我们需要加载两种或两种以上不同的布局,实现方法很简单:
- 重写 getViewTypeCount() – 返回你有多少个不同的布局
- 重写 getItemViewType(int) – 由position返回view type id
- 根据view item的类型,在getView中创建正确的convertView
代码:
1 public class MainActivity extends AppCompatActivity { 2 3 4 5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 10 toolbar.setTitle("测试"); 11 setSupportActionBar(toolbar); 12 13 ListView listView = (ListView) findViewById(R.id.listview); 14 listView.setAdapter(new ListviewAdapter()); 15 } 16 17 18 19 class ListviewAdapter extends BaseAdapter { 20 21 @Override 22 public int getCount() { 23 return 50; 24 } 25 26 @Override 27 public Object getItem(int position) { 28 return null; 29 } 30 31 @Override 32 public long getItemId(int position) { 33 return 0; 34 } 35 36 37 @Override 38 public View getView(int position, View convertView, ViewGroup parent) { 39 View view = null; 40 int type = getItemViewType(position); 41 switch (type) { 42 case 0: 43 view = LayoutInflater.from(MainActivity.this).inflate(R.layout.listviewitem, parent, false); 44 TextView tv = (TextView) view.findViewById(R.id.item_tv); 45 tv.setText("textView" + position); 46 break; 47 case 1: 48 view = LayoutInflater.from(MainActivity.this).inflate(R.layout.listviewpic, parent, false); 49 break; 50 } 51 return view; 52 } 53 54 @Override 55 public int getViewTypeCount() { 56 //多少种布局 57 return 2; 58 } 59 60 @Override 61 public int getItemViewType(int position) { 62 return position % 4 == 0 ? 1 : 0; 63 } 64 65 } 66 }
运行效果,每三个item一个分隔图片