传送门☞轮子的专栏☞转载请注明☞http://blog.csdn.net/leverage_1229

今天我们学习如何自定义TextView组件,让它既能显示文本,又能显示图像,达到“图文并茂”的效果。这种图文混搭的方式常常被用来展现新闻、文章、彩信等内容。下面给出该情景的案例:

1案例技术要点

1.1创建attrs.xml文件用于设置自定义组件的属性、类型和样式。
1.2利用android.content.res.TypedArray类将自定义组件装载到程序,以供程序调用。

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);

1.3布局文件引入自定义组件需要如下设置
自定义组件命名空间:

xmlns:custom="http://schemas.android.com/apk/res/com.custom.textview"

自定义组件标签:

<com.custom.textview.CustomTextView .../>

1.4构造一个HashMap数据结构,用于保存自定义组件的内容类型和值。

key:自定义组件的内容类型(image、text)

value:自定义组件的内容值(imageUrl,CharSequence)

1.5利用android.widget.LinearLayout.LayoutParams类用于设置组件的布局参数。这里需要根据显示内容的类型动态地设置组件的布局参数。

2案例代码陈列

2.1工程包目录

2.2AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.custom.textview"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="15" /><uses-permission android:name="android.permission.INTERNET"/><applicationandroid:icon="@drawable/ic_launcher"android:label="@string/app_name"><activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

2.3strings.xml

<resources><string name="app_name">自定义TextView实现图文并茂</string>
</resources>

2.4自定义TextView组件的属性类型样式文件:attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><declare-styleable name="customTextView"><attr name="image_width" format="dimension" /><attr name="image_height" format="dimension" /><attr name="text_color" format="color" /><attr name="text_size" format="dimension" /></declare-styleable>
</resources>

2.5main.xml

<?xml version="1.0" encoding="utf-8" ?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:custom="http://schemas.android.com/apk/res/com.custom.textview"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="@android:color/white" ><com.custom.textview.CustomTextViewandroid:id="@+id/textView"android:layout_width="match_parent"android:layout_height="wrap_content"custom:image_width="200dp"custom:image_height="50dp" /></LinearLayout>

2.6自定义组件类:CustomTextView.java

package com.custom.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 CustomTextView extends LinearLayout {private Context context;private TypedArray typedArray;private LayoutParams params;public CustomTextView(Context context) {super(context);}public CustomTextView(Context context, AttributeSet attrs) {super(context, attrs);this.context = context;this.setOrientation(LinearLayout.VERTICAL);// 从attrs.xml中获取自定义属性typedArray = context.obtainStyledAttributes(attrs, R.styleable.customTextView);}public void setText(ArrayList<HashMap<String, String>> data) {for (HashMap<String, String> hashMap : data) {String type = hashMap.get("type");String value = hashMap.get("value");// 如果内容类型是图片if (type.equals("image")) {// 设置图片显示宽高、集中int imageWidth = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_width, 100);int imageHeight = typedArray.getDimensionPixelOffset(R.styleable.customTextView_image_height, 100);ImageView imageView = new ImageView(context);params = new LayoutParams(imageWidth, imageHeight);params.gravity = Gravity.CENTER_HORIZONTAL;imageView.setLayoutParams(params);// 显示默认图片imageView.setImageResource(R.drawable.ic_launcher);// 将ImageView添加到CustomTextView中addView(imageView);// 开启工作线程异步加载图片new DownloadWork(value, imageView).start();} else if (type.equals("text")) {int textColor = typedArray.getColor(R.styleable.customTextView_text_color, 0xFF0000FF);float textSize = typedArray.getDimension(R.styleable.customTextView_text_size, 16);TextView textView = new TextView(context);textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));textView.setText(Html.fromHtml(value));textView.setTextColor(textColor);textView.setTextSize(textSize);addView(textView);}}}private class DownloadWork extends Thread {private String imageUrl;private ImageView imageView;public DownloadWork(String imageUrl, ImageView imageView) {this.imageUrl = imageUrl;this.imageView = imageView;}@Overridepublic void run() {URL url = null;Drawable drawable = null;int newImageWidth = 0;int newImageHeight = 0;try {url = new URL(imageUrl);drawable = Drawable.createFromStream(url.openStream(), "image");// 对图片进行缩放newImageWidth = drawable.getIntrinsicWidth() / 3;newImageHeight = drawable.getIntrinsicHeight() / 3;} catch (Exception e) {e.printStackTrace();}SystemClock.sleep(2000);HashMap<String, Object> map = new HashMap<String, Object>();map.put("imageView", imageView);map.put("drawable", drawable);Message msg = handler.obtainMessage();msg.obj = map;msg.arg1 = newImageWidth;msg.arg2 = newImageHeight;handler.sendMessage(msg);}}private Handler handler = new Handler() {public void handleMessage(Message msg) {@SuppressWarnings("unchecked")HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;ImageView imageView = (ImageView) map.get("imageView");LayoutParams params = new LayoutParams(msg.arg1, msg.arg2);params.gravity = Gravity.CENTER_HORIZONTAL;imageView.setLayoutParams(params);Drawable drawable = (Drawable) map.get("drawable");imageView.setImageDrawable(drawable);}};
}

2.7MainActivity.java

package com.custom.textview;import java.util.ArrayList;
import java.util.HashMap;import android.app.Activity;
import android.os.Bundle;public class MainActivity extends Activity {private final String text = " <p>  今年浙江卫视凭《中国好声音》一举做大" +",其巨大的影响力直接波及到了各家卫视“跨年晚会”的战略部署。日前" +",“跨年晚会”概念的鼻祖湖南卫视率先表示“退出跨年烧钱大战”。" +"但据湖南卫视内部人士透露,即使如此,今年的湖南跨年晚会也将会掂出“跨年季”这个概念" +",“也就是从12月27日到12月31日,连续五天,我们将相继用《百变大咖秀》、《快乐大本营》" +"、《女人如歌》、《天天向上》的特别节目来连续打造这个”季“的概念,直到12月31日的那场晚会。”</p>";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 采集显示内容数据ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String,String>>();HashMap<String, String> part1 = new HashMap<String, String>();part1.put("type", "image");part1.put("value", "http://www.linuxidc.com/upload/2012_12/121218101020341.png");HashMap<String, String> part2 = new HashMap<String, String>();part2.put("type", "text");part2.put("value", text);HashMap<String, String> part3 = new HashMap<String, String>();part3.put("type", "image");part3.put("value", "http://www.linuxidc.com/upload/2012_12/121218101020341.png");data.add(part1);data.add(part2);data.add(part3);CustomTextView customTextView = (CustomTextView) findViewById(R.id.textView);customTextView.setText(data);}
}

3案例效果展示

Android定制组件之图文展示之中国好声音相关推荐

  1. Android 用户界面---定制组件(Custom Components)

    基于布局类View和ViewGroup的基本功能,Android为创建自己的UI界面提供了先进和强大的定制化模式.首先,平台包含了各种预置的View和ViewGroup子类---Widget和layo ...

  2. Android四大组件之——Activity的生命周期(图文详解)

        转载请在文章开头处注明本博客网址:http://www.cnblogs.com/JohnTsai       联系方式:JohnTsai.Work@gmail.com       [Andro ...

  3. Android四大组件之——Activity(一)定义、状态和后退栈(图文详解)

    什么是Activity 关键字:应用组件.四大组件.用户界面,交互. An Activity is an application component that provides a screen wi ...

  4. Android最完整的仿QQ表情聊天图文展示代码示例

    安卓最完整的表情聊天特效(大家可以看我上一篇文章websocket的整合,这是他的后续) 首先我们需要知道安卓输入的是EditText 显示的内容是TextView, 但是TextView里面又只能显 ...

  5. Android 开源组件和第三方库汇总

    出自(https://github.com/Tim9Liu9/TimLiu-Android) TimLiu-Android 自己总结的Android开源项目及库. 1. github排名 https: ...

  6. Android 高级UI设计笔记08:Android开发者常用的7款Android UI组件(转载)

    Android开发是目前最热门的移动开发技术之一,随着开发者的不断努力和Android社区的进步,Android开发技术已经日趋成熟,当然,在Android开源社区中也涌现了很多不错的开源UI项目,它 ...

  7. Android 四大组件通信核心

    前言 系列文章: Android Activity创建到View的显示过程 Android 四大组件通信核心 Android 系统启动到App 界面完全展示终于明白(图文版) 我们知道Android ...

  8. android开发常用的组件,7款Android开发者常用的Android UI组件

    关注微信号:javalearns   随时随地学Java 或扫一扫 随时随地学Java Android开发是目前最热门的移动开发技术之一,随着开发者的不断努力和Android社区的进步,Android ...

  9. 深圳腾讯内部Jetpack宝典意外流出!极致经典,堪称Android架构组件的天花板

    简介 Jetpack是一套库.工具和指南,可以帮助开发者更轻松地编写优质应用.这些组件可以帮助开发者遵循最佳做法.让开发者摆脱编写样板代码的工作并简化复杂任务,以便开发者将精力集中放在所需的代码上. ...

最新文章

  1. 你需要知道的高性能并发框架Disruptor原理
  2. 一个困扰数学家30多年的分类问题,终于被解决了!
  3. TDD与FDD技术对比
  4. hibernate查询-基本查询
  5. boost::neighbor_bfs_visitor用法的测试程序
  6. jquery获取下拉框的值并传递给后端处理
  7. Function Programming - 柯里化(curry)
  8. 空间装扮代码_你多久没进过QQ空间了
  9. 厉害了!20年【科比NBA】生涯|数据分析
  10. jquery设为首页,加入收藏代码
  11. u12无线网卡linux驱动装不上,腾达(U12)USB无线网卡Linux驱动安装笔记
  12. stokes方程matlab,Navier-Stokes matlab 238万源代码下载- www.pudn.com
  13. poi设置excel表格边框
  14. python如何调用谷歌搜图api_python如何调用百度识图api
  15. 因为计算机限制无法访问U盘,U盘拒绝访问怎么办解决教程
  16. HTML设计网站首页
  17. pandas从入门到进阶
  18. 免费换背景app、在线修改图片像素、在线照片压缩网站
  19. 基于 VIVADO 的 AM 调制解调(3)仿真验证
  20. C++继承和派生笔记

热门文章

  1. python2 字符串函数_笔记六:python2字符串运算与函数
  2. 二叉搜索树的后序遍历
  3. 测试面试题,自动化测试与性能测试篇(附答案)
  4. node mysql登录注册_Node数据库入门(登录注册功能)
  5. 如果项目上线在上线期间出现BUG改怎么办?
  6. linux 消息队列_Linux消息队列
  7. 黑马博客——详细步骤(十二)项目功能的实现之文章评论和退出功能
  8. CSS基础——选择器【学习笔记】
  9. 剑指offer面试题[60]-将二叉树打印成多行
  10. H5测试是怎么做的?