本篇文章为大家展示了Android中怎么通过自定义ImageView添加文字说明,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
MyImageTextViewNew.java
public class MyImageTextViewNew extends LinearLayout {
private ImageView mImageView = null;
private TextView mTextView = null;
private int imageId;
private int textId, textColorId;
public MyImageTextViewNew(Context context) {
this(context, null);
}
public MyImageTextViewNew(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MyImageTextViewNew(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.setOrientation(LinearLayout.VERTICAL);//设置垂直排序
this.setGravity(Gravity.CENTER);//设置居中
if (mImageView == null) {
mImageView = new ImageView(context);
}
if (mTextView == null) {
mTextView = new TextView(context);
}
if (attrs == null)
return;
int count = attrs.getAttributeCount();
for (int i = 0; i < count; i++) {
String attrName = attrs.getAttributeName(i);//获取属性名称
//根据属性获取资源ID
switch (attrName) {
//显示的图片
case "image":
imageId = attrs.getAttributeResourceValue(i, 0);
break;
//显示的文字
case "text":
textId = attrs.getAttributeResourceValue(i, 0);
break;
//显示的文字的颜色
case "textColor":
textColorId = attrs.getAttributeResourceValue(i, 0);
break;
}
}
init();
}
/**
* 初始化状态
*/
private void init() {
this.setText(textId);
mTextView.setGravity(Gravity.CENTER);//字体居中
this.setTextColor(textColorId);
this.setImgResource(imageId);
addView(mImageView);//将图片控件加入到布局中
addView(mTextView);//将文字控件加入到布局中
}
/**
* 设置显示的图片
*
* @param resourceID 图片ID
*/
private void setImgResource(int resourceID) {
if (resourceID == 0) {
this.mImageView.setImageResource(0);
} else {
this.mImageView.setImageResource(resourceID);
}
}
/**
* 设置显示的文字
*
* @param text
*/
public void setText(int text) {
this.mTextView.setText(text);
}
/**
* 设置字体颜色(默认为黑色)
*
* @param color
*/
private void setTextColor(int color) {
if (color == 0) {
this.mTextView.setTextColor(Color.BLACK);
} else {
this.mTextView.setTextColor(getResources().getColor(color));
}
}
}
简单解释下..实际上就是在LinearLayout布局中添加ImageView和TextView
这个View也比较简单,代码中也有部分简易的说明.
下面可能还需要一个属性文件
imageText.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="imageText">
<attr name="image" format="integer" />
<attr name="text" format="integer" />
<attr name="textColor" format="integer" />
</declare-styleable>
</resources>
配置文件存放位置
下面展示使用方法
上述内容就是Android中怎么通过自定义ImageView添加文字说明,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。