Android-自定義TextView和異步加載圖片的實現

jopen 12年前發布 | 43K 次閱讀 Android Android開發 移動開發

實例:ConstomTextView

實現步驟:

1. 定義一個繼承LinearLayout的類:ConstomTextView

2. 在ConstomTextView類中自定義setText()方法

3.在setText方法中,通過TypedArray來獲取自定義屬性,來設置組件相應的參數

4.如果要在布局中顯示出圖片就應該定義ImageView,顯示出文本就定義TextView,以此類推

5. 最后要將組件通過addView()方法添加到布局當中。

6. 要實現圖片異步加載,需要定義一個線程類,通過Handler來進行數據交互,來達到UI的更新

項目運行效果:

    Android-自定義TextView和異步加載圖片的實現  2秒過后。。。Android-自定義TextView和異步加載圖片的實現

源代碼:MainActivity.java
    package com.wwj.textView;

import java.util.ArrayList;  
import java.util.HashMap;  

import android.os.Bundle;  
import android.app.Activity;  

public class MainActivity extends Activity {  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        /**********************測試數據**********************/  
        ArrayList<HashMap<String, String>> datas = new ArrayList<HashMap<String,String>>();  
        HashMap<String, String> hashMap1 = new HashMap<String, String>();  
        hashMap1.put("type", "image");  
        hashMap1.put("value", "http://www.taoqao.com/uploads/allimg/111216/1-111216101257.png");  
        HashMap<String, String> hashMap2 = new HashMap<String, String>();  
        hashMap2.put("type", "text");  
        hashMap2.put("value", newsbody);  
        HashMap<String, String> hashMap3 = new HashMap<String, String>();  
        hashMap3.put("type", "image");  
        hashMap3.put("value", "http://www.taoqao.com/uploads/allimg/111216/1-111216101257.png");  
        datas.add(hashMap1);  
        datas.add(hashMap2);  
        datas.add(hashMap3);  
      /*************************************************************************/  
        //獲取自定義組件的引用  
        ConstomTextView view = (ConstomTextView) findViewById(R.id.textView);  
        //調用ConstomTextView自定義的setText方法  
        view.setText(datas);  
    }  

    //新聞信息  
    private final String newsbody = " <p>  今年浙江衛視憑《中國好聲音》一舉做大" +  
            ",其巨大的影響力直接波及到了各家衛視“跨年晚會”的戰略部署。日前" +  
            ",“跨年晚會”概念的鼻祖湖南衛視率先表示“退出跨年燒錢大戰”。" +  
            "但據湖南衛視內部人士透露,即使如此,今年的湖南跨年晚會也將會掂出“跨年季”這個概念" +  
            ",“也就是從12月27日到12月31日,連續五天,我們將相繼用《百變大咖秀》、《快樂大本營》" +  
            "、《女人如歌》、《天天向上》的特別節目來連續打造這個”季“的概念,直到12月31日的那場晚會。”</p>";  
}  </pre></span>源代碼:ConstomTextView.java<pre class="brush:java; toolbar: true; auto-links: false;">    package com.wwj.textView;  

import java.net.URL;  
import java.util.ArrayList;  
import java.util.HashMap;  

import android.content.Context;  
import android.content.res.TypedArray;  
import android.graphics.drawable.Drawable;  
import android.os.Handler;  
import android.os.Message;  
import android.os.SystemClock;  
import android.text.Html;  
import android.util.AttributeSet;  
import android.view.Gravity;  
import android.widget.ImageView;  
import android.widget.LinearLayout;  
import android.widget.TextView;  

public class ConstomTextView extends LinearLayout{  

    //上下文對象  
    private Context mContext;  
    //聲明TypedArray的引用  
    private TypedArray mTypedArray;  
    //布局參數  
    private LayoutParams params;  

    public ConstomTextView(Context context) {  
        super(context);  
    }  

    public ConstomTextView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        this.mContext = context;  
        this.setOrientation(LinearLayout.VERTICAL);  
        //從attrs.xml文件中那個獲取自定義屬性  
        mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.constomTextView);  
    }  

    public void setText(ArrayList<HashMap<String, String>> datas) {  
        //遍歷ArrayList  
        for(HashMap<String, String> hashMap : datas) {  
            //獲取key為"type"的值  
            String type = hashMap.get("type");  
            //如果value=imaeg  
            if(type.equals("image")){  
                //獲取自定義屬性屬性  
                int imagewidth = mTypedArray.getDimensionPixelOffset(R.styleable.constomTextView_image_width, 100);  
                int imageheight = mTypedArray.getDimensionPixelOffset(R.styleable.constomTextView_image_height, 100);  
                ImageView imageView = new ImageView(mContext);  
                params = new LayoutParams(imagewidth, imageheight);  
                params.gravity = Gravity.CENTER_HORIZONTAL; //居中  
                imageView.setLayoutParams(params);  
                //顯示圖片  
                imageView.setImageResource(R.drawable.ic_constom);  
                //將imageView添加到LinearLayout當中  
                addView(imageView);  
                //啟動異步線程更新異步顯示圖片信息  
                new DownloadPicThread(imageView, hashMap.get("value")).start();  
            }  
            else {  
                float textSize = mTypedArray.getDimension(R.styleable.constomTextView_textSize, 16);  
                int textColor = mTypedArray.getColor(R.styleable.constomTextView_textColor, 0xFF0000FF);  
                TextView textView = new TextView(mContext);  
                textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));  
                textView.setText(Html.fromHtml(hashMap.get("value")));  
                textView.setTextSize(textSize);     //設置字體大小  
                textView.setTextColor(textColor);   //設置字體顏色  
                addView(textView);  
            }  
        }  
    }  

    private Handler handler = new Handler() {  
        public void handleMessage(android.os.Message msg) {  
            @SuppressWarnings("unchecked")  
            HashMap<String, Object> hashMap = (HashMap<String, Object>) msg.obj;  
            ImageView imageView = (ImageView) hashMap.get("imageView");  
            LayoutParams params = new LayoutParams(msg.arg1, msg.arg2);  
            params.gravity = Gravity.CENTER_HORIZONTAL; //居中  
            imageView.setLayoutParams(params);  
            Drawable drawable = (Drawable) hashMap.get("drawable");  
            imageView.setImageDrawable(drawable);       //顯示圖片  
        };  
    };  

    /** 
     * 定義一個線程類,異步加載圖片 
     * @author Administrator 
     * 
     */  
    private class DownloadPicThread extends Thread {  
        private ImageView imageView;  
        private String mUrl;  


        public DownloadPicThread(ImageView imageView, String mUrl) {  
            super();  
            this.imageView = imageView;  
            this.mUrl = mUrl;  
        }  


        @Override  
        public void run() {  
            // TODO Auto-generated method stub  
            Drawable drawable = null;  
            int newImgWidth = 0;  
            int newImgHeight = 0;  
            try {  
                drawable = Drawable.createFromStream(new URL(mUrl).openStream(), "image");  
                //對圖片進行縮放  
                newImgWidth = drawable.getIntrinsicWidth() / 3;  
                newImgHeight = drawable.getIntrinsicHeight() / 3;  
            } catch (Exception e) {  
                // TODO: handle exception  
                e.printStackTrace();  
            }  
            //讓線程休眠2秒  
            SystemClock.sleep(2000);  
            //使用Handler更新UI  
            Message msg = handler.obtainMessage();  
            HashMap<String, Object> hashMap = new HashMap<String, Object>();  
            hashMap.put("imageView", imageView);  
            hashMap.put("drawable", drawable);  
            msg.obj = hashMap;  
            msg.arg1 = newImgWidth;  
            msg.arg2 = newImgHeight;  
            handler.sendMessage(msg);  
        }  
    }  

}  </pre>自定義屬性:/values/attrs.xml<pre class="brush:xml; toolbar: true; auto-links: false;">    <?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <declare-styleable name="constomTextView">  
        <attr name="image_width" format="dimension"/>  
        <attr name="image_height" format="dimension"/>  
        <attr name="textColor" format="color"/>  
        <attr name="textSize" format="dimension"/>  
    </declare-styleable>  
</resources>  </pre>布局文件:main.xml<pre class="brush:xml; toolbar: true; auto-links: false;">    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:wwj="http://schemas.android.com/apk/res/com.wwj.textView"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/LinearLayout1"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical" >  

    <com.wwj.textView.ConstomTextView  
        android:id="@+id/textView"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"   
        wwj:image_width="200dip"  
        wwj:image_height="52dip"/>  

</LinearLayout>  </pre>來自:http://blog.csdn.net/wwj_748/article/details/8195975
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!