Android开发中ListView的使用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wpwbb510582246/article/details/52717855

一、ListView的使用方法详解

1、定义一个布局并将其初始化,同时设置它的一些属性

  1. private LinearLayout llInormation;
  1. llInormation=new LinearLayout(MainActivity.this);
  2. llInormation.setOrientation(LinearLayout.HORIZONTAL);
  3. llInormation.setPadding(5, 5, 5, 5);

2、定义并初始化ListView的适配器

  1. BaseAdapter baseAdapter=new BaseAdapter() {
  2. @Override
  3. public View getView(int position, View convertView, ViewGroup parent) {
  4. llInormation=new LinearLayout(MainActivity.this);
  5. return llInormation;
  6. }
  7. @Override
  8. public long getItemId(int position) {
  9. return 0;
  10. }
  11. @Override
  12. public Object getItem(int position) {
  13. return null;
  14. }
  15. @Override
  16. public int getCount() {
  17. return 5;
  18. }
  19. };

3、定义一些控件并将其初始化,同时设置它的一些属性,然后向布局中添加控件(这里定义一个ImageView控件和TextView控件)

  1. private ImageView imgPeople;
  2. private TextView tvChoice;
  1. // 定义并初始化ImageView控件,同时设置它的一些属性,然后向布局中添加ImageView控件
  2. imgPeople=new ImageView(MainActivity.this);
  3. imgPeople.setImageDrawable(getResources().getDrawable(imgId[position]));
  4. imgPeople.setLayoutParams(new Gallery.LayoutParams(210, 240));
  5. llInormation.addView(imgPeople);
  1. // 定义并初始化TextView控件,同时设置它的一些属性,然后向布局中添加TextView控件
  2. tvChoice=new TextView(MainActivity.this);
  3. tvChoice.setText(getResources().getText(imgInfoId[position]));
  4. tvChoice.setTextSize(24);
  5. tvChoice.setTextColor(MainActivity.this.getResources().getColor(R.color.white));
  6. tvChoice.setGravity(Gravity.LEFT);
  7. tvChoice.setPadding(5, 5, 5, 5);
  8. llInormation.addView(tvChoice);

4、设置ListView的适配器

 
 
  1. lvInformation.setAdapter(baseAdapter);

二、示例

1、效果

2、源代码

 

源代码下载地址:http://download.csdn.net/detail/wpwbb510582246/9637881

 

由于本人初写博客,写的不好的地方还请大家能批评指正,希望能和大家相互学习、相互交流、共同成长。

猜你喜欢

转载自blog.csdn.net/wpwbb510582246/article/details/52717855