Android-自定义TextView和异步加载图片的实现


实例: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.linuxboy.net/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.linuxboy.net/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>";
}

  • 1
  • 2
  • 3
  • 下一页

相关内容