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

最近在回顾Android的基础知识,就把一些常见的知识点整理一下,以后忘了也可以翻出来看一看。

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

   

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

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

布局文件:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2 android:layout_width="match_parent"
 3 android:layout_height="match_parent"
 4 android:orientation="vertical">
 5 <TextView
 6 android:id="@+id/tv_text"
 7 android:layout_width="wrap_content"
 8 android:layout_height="wrap_content"
 9 android:layout_gravity="center"
10 android:text="text"
11 android:textSize="30dp"/>
12 <Button
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:text="show Image"
16 android:textSize="25dp"
17 android:layout_gravity="center"
18 android:onClick="click"/>
19 </LinearLayout>

 

Java代码:

 1 private TextView tv_text;
 2 private CharSequence charSequence;
 3 
 4 @Override
 5 protected void onCreate(Bundle savedInstanceState) {
 6 super.onCreate(savedInstanceState);
 7 setContentView(R.layout.textview_layout);
 8 tv_text= (TextView) findViewById(R.id.tv_text);
 9 charSequence = Html.fromHtml("<img>", new Html.ImageGetter() {
10 @Override
11 public Drawable getDrawable(String source) {
12 // 装载图像资源
13 Drawable drawable = getResources().getDrawable(R.drawable.kobe);
14 // 设置要显示图像的大小(按原大小显示)
15 drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
16 return drawable;
17 }
18 }, null);
19 }
20 
21 public void click(View view)
22 {
23 tv_text.setText(charSequence);
24 }

 

运行效果图: 

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

   

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

下面是一个使用的事例:

 

1 <?xml version="1.0" encoding="utf-8"?>
2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
3 
4 <item android:state_pressed="true"
5 android:drawable="@android:color/holo_red_dark"/><!-- 表示被点击状态-->
6 <item android:drawable="@android:color/black"/> <!-- 表示默认状态-->
7 </selector>

 

posted @ 2016-03-14 22:07  Vonnie_Jade  阅读(356)  评论(0编辑  收藏  举报