import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int TYPE_0 = 0; private static final int TYPE_1 = 1; private ArrayList<String> strings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.listview); strings = new ArrayList<>(); for (int i=0;i<20;i++){ strings.add("这是条目"+i); } MyAdapter adapter = new MyAdapter(); listView.setAdapter(adapter); } private class MyAdapter extends BaseAdapter{ @Override public int getCount() { return strings.size(); } @Override public Object getItem(int i) { return strings.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { //得到指定条目的布局类型 int type = getItemViewType(i); ViewHolder1 holder1=null; ViewHolder2 holder2=null; switch (type){ case 0: if (view==null){ view=View.inflate(MainActivity.this,R.layout.listview_items,null); holder1=new ViewHolder1(); holder1.image1=view.findViewById(R.id.itemImage1); holder1.text1=view.findViewById(R.id.itemText1); view.setTag(holder1); }else{ holder1= (ViewHolder1) view.getTag(); } break; case 1: if (view==null){ view=View.inflate(MainActivity.this,R.layout.listview_items2,null); holder2=new ViewHolder2(); holder2.image2=view.findViewById(R.id.itemImage2); holder2.text2=view.findViewById(R.id.itemText2); view.setTag(holder2); }else{ holder2= (ViewHolder2) view.getTag(); } break; } switch (type){ case 0: holder1.image1.setImageResource(R.mipmap.ic_launcher_round); holder1.text1.setText(strings.get(i)); break; case 1: holder2.image2.setImageResource(R.mipmap.ic_launcher_round); holder2.text2.setText(strings.get(i)); break; } return view; } class ViewHolder1{ private ImageView image1; private TextView text1; } class ViewHolder2{ private ImageView image2; private TextView text2; } @Override public int getItemViewType(int position) { //得到某个条目的类型 if (position%2==0){ return TYPE_0; }else{ return TYPE_1; } } @Override public int getViewTypeCount() { //指定你要在这个当前这个ListView显示几种类型的条目 return 2; } } }
Listview(多条目展示)
最新推荐文章于 2017-07-25 09:40:43 发布