1. 程式人生 > >兩個介面實現多條目+ImageLoad圖片圓形效果

兩個介面實現多條目+ImageLoad圖片圓形效果

開始佈局

兩個介面為頭條,國內。需要載入完頭條資料,再展示國內資料

頭條佈局如下(不帶圖片)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    >

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="標題"
        android:textColor="#000"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@id/author"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:id="@+id/author"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="作者"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/title"
        />
</android.support.constraint.ConstraintLayout>

國內佈局如下(包含圖片)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    >

    <ImageView
        android:id="@+id/iv"
        android:layout_width="160dp"
        android:layout_height="100dp"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="標題"
        android:textColor="#000"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@id/author"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/iv"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:id="@+id/author"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="作者"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/iv"
        app:layout_constraintTop_toBottomOf="@id/title"
        />
</android.support.constraint.ConstraintLayout>

activity-main只有一個listview

java程式碼

package com.bwie.xuexinxin;


import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;

import com.google.gson.Gson;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtilsHC4;

import java.io.IOException;
import java.util.ArrayList;

import adapter.MAdapter;
import bean.News;

public class MainActivity extends AppCompatActivity {
   private MAdapter ma;
   private ListView lv;
   private ArrayList<News.ResultBean.DataBean> list;
    News news;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=findViewById(R.id.lv);
        list=new ArrayList<News.ResultBean.DataBean>();
        ma=new MAdapter(MainActivity.this,list);
      lv.setAdapter(ma);
        //獲取網路資料
        loadData();

    }

    private void loadData() {
        @SuppressLint("StaticFieldLeak") AsyncTask<String,String,ArrayList<News.ResultBean.DataBean>> asyncTask=new AsyncTask<String, String, ArrayList<News.ResultBean.DataBean>>() {
            @Override
            protected ArrayList<News.ResultBean.DataBean> doInBackground(String... strings) {

               //1 建立client
                CloseableHttpClient httpClient= HttpClients.createDefault();
               for (String url:strings){
                   //2.建立請求
                   HttpUriRequest request =RequestBuilder.get().setUri(url).build();

                   try {
                       //3 執行請求
                       CloseableHttpResponse response=httpClient.execute(request);
                       //4.獲取響應結果
                       int statusCode=response.getStatusLine().getStatusCode();
                       if(statusCode==200){
                           publishProgress("獲取: " + url + "響應成功");
                           String textString= EntityUtilsHC4.toString(response.getEntity());
                           Gson gson=new Gson();
                           news=gson.fromJson(textString,News.class);
                           ArrayList<News.ResultBean.DataBean> data= (ArrayList<News.ResultBean.DataBean>) news.getResult().getData();
                           list.addAll(data);


                           publishProgress("獲取: " + url + "資料成功");
                       } else {
                           publishProgress("獲取: " + url + "響應失敗");
                       }

                   } catch (IOException e) {
                       e.printStackTrace();
                   }

               }

                return list;
            }
            @Override
            protected void onProgressUpdate(String... values) {
                super.onProgressUpdate(values);
                Log.e("TEST", "任務進度更新: " + values[0]);
            }
            //資料傳遞到主執行緒,更新UI
            protected void onPostExecute(ArrayList<News.ResultBean.DataBean> dataBeans) {
                super.onPostExecute(dataBeans);

                ma.notifyDataSetChanged();

            }


        };
        //兩個介面
        asyncTask.execute(
                "http://result.eolinker.com/k2BaduF2a6caa275f395919a66ab1dfe4b584cc60685573?uri=tt",
                "http://result.eolinker.com/k2BaduF2a6caa275f395919a66ab1dfe4b584cc60685573?uri=gn"
        );

    }
}

ImageLoad配置程式碼

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoader.getInstance().init(ImageloadConfigs.getCon(this));
    }
}
 
 
​
public static ImageLoaderConfiguration getCon(Context context) {
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(context)
        //內在快取額外選項, 最大的寬度,高度
        //.memoryCacheExtraOptions(480, 800) // default = device screen dimensions 記憶體快取檔案的最大長寬
        //.diskCacheExtraOptions(480, 800, null)  // 本地快取的詳細資訊(快取的最大長寬),最好不要設定這個
        //執行緒池配置
        //.taskExecutor()
        //.taskExecutorForCachedImages()
        //.threadPoolSize(3) // default  執行緒池內載入的數量
        //.threadPriority(Thread.NORM_PRIORITY - 2) // default 設定當前執行緒的優先順序
        //任務處理優先順序 Fist In Fist Out
        //.tasksProcessingOrder(QueueProcessingType.FIFO) // default
        //記憶體中不快取一張圖片的多個尺寸大小
        //.denyCacheImageMultipleSizesInMemory()
        //內在快取策略
        //.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通過自己的記憶體快取實現
        //記憶體快取大小
        //.memoryCacheSize(2 * 1024 * 1024)  // 記憶體快取的最大值
        //內在快取大小:佔用百分比
        .memoryCacheSizePercentage(13) // default
        //磁碟快取策略
        //.diskCache(new LruDiskCache()) // default 可以自定義快取路徑
        //磁碟快取大小
        .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)快取的最大值
        //.diskCacheFileCount(100)  // 可以快取的檔案數量
        // default為使用HASHCODE對UIL進行加密命名, 還可以用MD5(new Md5FileNameGenerator())加密
        //.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
        //.imageDownloader(new BaseImageDownloader(context)) // default
        //(new BaseImageDecoder(false)) // default
        //載入具體圖片時的一些配置
        //.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
		.defaultDisplayImageOptions(getOps)
		//快取圖片到指定資料夾
		 File file=new File(Environment.getExternalStorageDirectory().getPath()+"/imagefile")
		 .diskCache(new UnlimitedDiskCache(file))
        .writeDebugLogs() // 列印debug log
        .build();
 
    return configuration;
  }
 
  public static DisplayImageOptions getOps(Context context) {
    DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder()
        //是否快取
        .cacheInMemory(true)
        .cacheOnDisk(true)
        //RGB 565   r紅色佔5   g綠色佔6   b藍色佔5  -> 2位元組
        //alpha
        //ARGB 4444    4 4 4 4  -> 2位元組
        //ARGB 8888    -> 4位元組
 
        //10 * 10 用rgb565 -> 10*10*2
 
        .bitmapConfig(Bitmap.Config.RGB_565)
        //載入時、載入錯誤時展示什麼內容
        .showImageOnLoading(R.mipmap.ic_launcher)
        .showImageOnFail(R.mipmap.ic_launcher)
        //
        .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
        //載入效果
        //ctrl + p
        .displayer(new CircleBitmapDisplayer())
        .build();
 
    //ctrl + h
    //BitmapDisplayer;
    return displayImageOptions;
  }
 
​

Adapter多加了getItemViewType和getViewTypeCount()方法進行多條目載入

package adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bwie.xuexinxin.ImageloadConfigs;
import com.bwie.xuexinxin.MainActivity;
import com.bwie.xuexinxin.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;

import bean.News;

public class MAdapter extends BaseAdapter{
    private MainActivity mainActivity;
    private ArrayList<News.ResultBean.DataBean> list;

    public MAdapter(MainActivity mainActivity, ArrayList<News.ResultBean.DataBean> list) {
        this.mainActivity = mainActivity;
        this.list = list;
    }


    //當前item是什麼型別
    @Override
    public int getItemViewType(int position) {
        News.ResultBean.DataBean data= (News.ResultBean.DataBean) getItem(position);
        //頭條型別
        if(data.isTT()){
            return super.getItemViewType(position);
        }
        //國內型別
        if (data.isCN()) {
            return 1;
        }
        return 1;
    }

    @Override
    public int getViewTypeCount() {
        return super.getViewTypeCount()+1;
    }

   
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder vh=null;
        if(convertView==null){

            convertView=View.inflate(mainActivity,getItemViewType(position)==0?R.layout.tt_item:R.layout.gn_item,null);
           vh=new ViewHolder(convertView);

        } else {
            vh= (ViewHolder) convertView.getTag();
        }
        News.ResultBean.DataBean data= (News.ResultBean.DataBean) getItem(position);
        vh.bindData(data);
        return convertView;
    }
   
    @Override
    public int getCount() {

        return list.size();
    }

  
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

   
    @Override
    public long getItemId(int position) {
        return position;
    }
    public class ViewHolder {
        TextView title;
        TextView author;
        ImageView iv;

        public ViewHolder(View viewItem) {
            title=viewItem.findViewById(R.id.title);
            author=viewItem.findViewById(R.id.author);
            //國內
            iv=viewItem.findViewById(R.id.iv);
            viewItem.setTag(this);
        }
        public void bindData(News.ResultBean.DataBean data){
            title.setText(data.getTitle());
            author.setText(data.getAuthor_name());
            if(data.isCN()){
                ImageLoader.getInstance().displayImage(data.getThumbnail_pic_s(),iv, ImageloadConfigs.getOps(mainActivity));

            }

        }
    }


}

​

效果: