欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-06-03 19:16:23
本文实例讲述了android开发实现listview和adapter配合显示图片和文字列表功能。分享给大家供大家参考,具体如下: 实际效果: 布局文件:...

本文实例讲述了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程序设计有所帮助。