TextView是一个非常强大的控件,有时须要在一个控件中同一时候显示图片和文字,使用TextView非常easy实现。
方法一:
聊天软件比方QQ一般都会有发送表情的功能,使用SpannableString+ImageSpan能够非常easy实现
- private void showImageFace(String s,View v)
- {
- Bitmap bitmap;
- ImageSpan imageSpan;
-
- SpannableString spannableString = new SpannableString(s);
- for(int i=0;i<name.length;i++)
- {
- Log.i("MainActivity", "查找:"+name[i]);
- int j=0;
- int start=0;
- while(s.indexOf(name[i],start)>=0)
- {
- start = s.indexOf(name[i],start);
- bitmap = BitmapFactory.decodeResource(getResources(), ids[i]);
- imageSpan = new ImageSpan(this, bitmap);
-
- spannableString.setSpan(imageSpan, start-1, start+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- start=start+3;
- }
- }
- ((TextView)v).setText(spannableString);
- }
注:有时须要给TextView中的个别字设置为超链接,或者设置个别字的颜色、字体等,都能够借助SpannableString对象实现。
方法二:
在XML文件里直接配置即可了
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableLeft="@drawable/jface_fastcry"
- android:drawableBottom="@drawable/jface_giddy"
- android:drawableRight="@drawable/jface_girl_cute"
- android:drawableTop="@drawable/jface_girl_cry"
- android:gravity="center_vertical|center_horizontal"
- android:text="中间"
- />
方法三:
扩展TextView控件,复写onDraw方法
- protected void onDraw(Canvas canvas)
- {
-
- super.onDraw(canvas);
- if(bitmap!=null)
- {
- canvas.drawBitmap(bitmap, 0, 0, null);
- Paint paint =new Paint();
- paint.setColor(0x77000000);
- canvas.drawRect(0, getHeight()-getTextSize()-getTextSize()/3,
- getWidth(), getHeight(), paint);
- }
- if(text!=null)
- {
- Paint paint =new Paint();
- paint.setColor(Color.WHITE);
- canvas.drawText(text, (getWidth()-text.length()*getTextSize())/2,
- getHeight()-getTextSize()/3, paint);
- }
-
- }
效果图片:
代码链接:
http://download.csdn.net/detail/tangnengwu/7238325