Android开发实现ListView和adapter配合显示图片和文字列表功能示例

发布时间:2020-10-23 13:24:43 作者:水中鱼之1999
来源:脚本之家 阅读:366

本文实例讲述了Android开发实现ListView和adapter配合显示图片和文字列表功能。分享给大家供大家参考,具体如下:

实际效果:

Android开发实现ListView和adapter配合显示图片和文字列表功能示例

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity"
  android:orientation="vertical">
    <!--使用红色得分割条-->
    <ListView
      android:id="@+id/list1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:divider="#f00"
      android:dividerHeight="2px"
      android:headerDividersEnabled="false">
    </ListView>
    <!--用于存放和发送新的信息-->
    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_marginBottom="0dp"
      android:background="#66ffffff"
      android:orientation="vertical">
        <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="vertical">
            <!--设置最大行数-->
            <EditText
              android:id="@+id/ifo_edit"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:hint="请输入内容"
              android:maxLines="6"
              android:textColorHint="#c0c0c0" />
            <!--存放新的图片-->
            <ImageView
              android:id="@+id/ifo_image"
              android:layout_width="130dp"
              android:layout_height="110dp"
              android:src="@drawable/addphoto" />
        </LinearLayout>
        <RelativeLayout
          android:layout_width="wrap_content"
          android:layout_height="wrap_content">
            <!--点击取消发送消息-->
            <Button
              android:id="@+id/delete"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentLeft="true"
              android:layout_gravity="left"
              android:text="取消"
              android:textSize="16sp" />
            <!--点击发送消息-->
            <Button
              android:id="@+id/send"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:text="发送"
              android:textSize="16sp" />
        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>

代码实现部分:

public class MainActivity extends AppCompatActivity {
  //list表
  private List<Informations> informationsList01 = new ArrayList<>();
  //当前消息列表
  ListView list01 ;
  //消息发送栏
  EditText editText01 ;
  //存放图片
  ImageView imageView01;
  //消息发送按钮
  Button button01_send ;
  //记录数组长度
  int arr_num = 0;
  //定义一个数组
  String[] arr1 = new String[arr_num];
  //从相册获得图片
  Bitmap bitmap;
  //判断返回到的Activity
  private static final int IMAGE_REQUEST_CODE = 0;
  //图片路径
  private String path ;
  private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
      if((Integer)msg.obj==0){
        imageView01.setImageBitmap(bitmap);
      }
      super.handleMessage(msg);
    }
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list01 = (ListView) findViewById(R.id.list1);
    editText01 = (EditText) findViewById(R.id.ifo_edit);
    imageView01 = (ImageView) findViewById(R.id.ifo_image);
    button01_send = (Button) findViewById(R.id.send);
    imageView01.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if(ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
          ActivityCompat.requestPermissions(MainActivity.this,new String[]{
              Manifest.permission.WRITE_EXTERNAL_STORAGE
          },1);
        }
        Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
      }
    });
    button01_send.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if(((BitmapDrawable) ((ImageView) imageView01).getDrawable()).getBitmap() != null
            || editText01.getText().toString() != null){
          Informations xiaochouyu = new Informations(
              ((BitmapDrawable) ((ImageView) imageView01).getDrawable()).getBitmap(),
              editText01.getText().toString());
          informationsList01.add(xiaochouyu);
          EssayAdapter adapter = new EssayAdapter(MainActivity.this,
              R.layout.array_list,informationsList01);
          list01.setAdapter(adapter);
          editText01.setText("");
          imageView01.setImageBitmap(null);
          imageView01.setImageResource(R.drawable.addphoto);
        }
      }
    });
  }
  /*定义一个Handler,定义延时执行的行为*/
  public void chnage(){
    new Thread(){
      @Override
      public void run() {
        while ( bitmap == null ){
          bitmap = BitmapFactory.decodeFile(path);
          Log.v("qwe","123");
        }
        Message message = handler.obtainMessage();
        message.obj = 0;
        handler.sendMessage(message);
      }
    }.start();
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //在相册里面选择好相片之后调回到现在的这个activity中
    switch (requestCode) {
      case IMAGE_REQUEST_CODE://这里的requestCode是我自己设置的,就是确定返回到那个Activity的标志
        if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
          try {
            Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            path = cursor.getString(columnIndex); //获取照片路径
            cursor.close();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            bitmap = BitmapFactory.decodeFile(path,options);
            imageView01.setImageBitmap(bitmap);
            chnage();
            Toast.makeText(MainActivity.this,path,Toast.LENGTH_SHORT).show();
          } catch (Exception e) {
            // TODO Auto-generatedcatch block
            e.printStackTrace();
          }
        }
        break;
    }
  }
  @TargetApi(19)
  private void handleImageOmKitKat(Intent data){
    String imagePath = null;
    Uri uri = data.getData();
    if (DocumentsContract.isDocumentUri(this,uri)){
      //如果document类型是U日,则通过document id处理
      String docId = DocumentsContract.getDocumentId(uri);
      if ("com.android.providers.media.documents".equals(uri.getAuthority())){
        String id = docId.split(":")[1];//解析出数字格式id
        String selection = MediaStore.Images.Media._ID + "=" + id;
        imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
      }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
        Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
        imagePath = getImagePath(contentUri,null);
      }
    }else if ("content".equalsIgnoreCase(uri.getScheme())){
      //如果是普通类型 用普通方法处理
      imagePath = getImagePath(uri,null);
    }else if ("file".equalsIgnoreCase(uri.getScheme())){
      //如果file类型位uri直街获取图片路径即可
      imagePath = uri.getPath();
    }
    displayImage(imagePath);
  }
  private void handleImageBeforeKitKat(Intent data){
    Uri uri = data.getData();
    String imagePath = getImagePath(uri,null);
    displayImage(imagePath);
  }
  private String getImagePath(Uri uri, String selection){
    String path = null;
    //通过Uri和selection来获取真实图片路径
    Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null){
      if (cursor.moveToFirst()){
        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
      }
      cursor.close();
    }
    return path;
  }
  private void displayImage(String imagePath){
    if (imagePath != null){
      Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
      imageView01.setImageBitmap(bitmap);
    }else {
      Toast.makeText(MainActivity.this,"fail to get image",Toast.LENGTH_SHORT).show();
    }
  }
}

Adapter 配试器:

public class EssayAdapter extends ArrayAdapter<Informations> {
  private int resourceId;
  public EssayAdapter(Context context, int textViewResourceId,
            List<Informations> objects){
    super(context, textViewResourceId, objects);
    resourceId = textViewResourceId;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    Informations informations = getItem(position);
    View view = LayoutInflater.from(getContext()).inflate(resourceId,parent, false);
    ImageView informationImage = (ImageView) view.findViewById(R.id.image);
    TextView informationEssay = (TextView) view.findViewById(R.id.essay);
    informationImage.setImageBitmap(informations.getImageBitmap());
    informationEssay.setText(informations.getEssay());
    return view;
  }
}

Information类:

包括 Bitmap 和 Essay 两个私有变量

public class Informations {
  //文体
  private String essay;
  //图片
  private Bitmap imageId;
  Informations(Bitmap imageId, String essay){
    this.imageId = imageId;
    this.essay = essay;
  }
  Informations(){
    this.essay = null;
    this.imageId = null;
  }
  public String getEssay() {
    return essay;
  }
  public void setEssay(String essay) {
    this.essay = essay;
  }
  public Bitmap getImageBitmap() {
    return imageId;
  }
  public void setImageBitmap(Bitmap imageId) {
    this.imageId = imageId;
  }
}

权限:

<!--获取照片权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android控件用法总结》、《Android开发入门与进阶教程》、《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android数据库操作技巧总结》及《Android资源操作技巧汇总》

希望本文所述对大家Android程序设计有所帮助。

推荐阅读:
  1. 关于ListView 自定义 Adapter的问题
  2. Vue如何实现搜索和新闻列表功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android listview adapter

上一篇:spring mvc中注解@ModelAttribute的妙用分享

下一篇:Java实现两人五子棋游戏(二) 画出棋盘

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》