歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android-自定義TextView和異步加載圖片的實現

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

日期:2017/3/1 10:04:54   编辑:Linux編程

實例:ConstomTextView

實現步驟:

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

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

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

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

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

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

項目運行效果:

2秒過後。。

源代碼: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.linuxidc.com/upload/2012_12/121218101020341.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.linuxidc.com/upload/2012_12/121218101020341.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>";
}

Copyright © Linux教程網 All Rights Reserved