ListView加载多种布局

Listview加载单一的item 布局有时候不能完全满足业务需求,我们需要加载两种或两种以上不同的布局,实现方法很简单:

重写 getViewTypeCount() – 返回你加载 不同的布局的个数

重写 getItemViewType(int) – 根据position返回view的type id

根据view item的类型,在getView中创建正确的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;

}

}

}


运行效果,每三个item一个分隔图片

你可能感兴趣的:(ListView加载多种布局)