您的位置:首页 > 移动开发 > Android开发

Android中的一些基础知识(三)

2016-03-14 22:07 453 查看
最近在回顾Android的基础知识,就把一些常见的知识点整理一下,以后忘了也可以翻出来看一看。

在TextView中显示图像(使用< img>标签)

在TextView中显示图片的方法有许多种,常见的有通过View.setBackground()来设置背景、在onDraw方法中绘制。这里我讲一下用< img>标签来设置图像。

TextView可以通过富文本标签来显示富文本信息,这种标签类似于HTML标签,TextView只支持有限的几种显示富文本的方式。在这里,我们通过 Html.fromHtml方法将这些资源转换成CharSequence,最后同text.setText()方法来显示图像。不多说了,直接上代码:

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="text"
android:textSize="30dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show Image"
android:textSize="25dp"
android:layout_gravity="center"
android:onClick="click"/>
</LinearLayout>


Java代码:

private TextView tv_text;
private CharSequence charSequence;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.textview_layout);
tv_text= (TextView) findViewById(R.id.tv_text);
charSequence = Html.fromHtml("<img>", new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
// 装载图像资源
Drawable drawable = getResources().getDrawable(R.drawable.kobe);
// 设置要显示图像的大小(按原大小显示)
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
}, null);
}

public void click(View view)
{
tv_text.setText(charSequence);
}


运行效果图:



使用StateListDrawable(通常会称为使用selector)

我们经常会给Button设置一个selector。StateListDrawable表示Drawable的集合,集合中的每个Drawable都对应着View的一种状态,系统会根据View的状态来给View设定相应的Drawable。需要强调的是:系统会跟据View当前的状态从selector中选择对应的item,每个item对应着一个具体的Drawable,系统会自上而下的查找,知道找到第一条匹配的item。一般来说默认的状态都会放在最后并且不附带任何状态,这样当其他item都无法匹配的时候系统会选用默认的item。(一般不要把默认的item放在第一条,因为系统会一直选用这个默认的状态)。

下面是一个使用的事例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
android:drawable="@android:color/holo_red_dark"/><!-- 表示被点击状态-->
<item android:drawable="@android:color/black"/> <!-- 表示默认状态-->
</selector>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: