---
title: "android自定义view 实现TextView 中文粗体 ."
author: "white__cat"
date: "2012-03-09T15:55:05Z"
tags: []
categories: ["移动开发"]
slug: "android-view-textview"
draft: false
lastmod: "2012-03-09T15:55:28Z"
id: 1447809
url: "https://white--cat.iteye.com/blog/1447809"
---

这是我在别人代码上修改的。。

 

首先android textview的粗体效果对于汉字不知道为什么的没用用处 设置了也没什么变化,然则这只对英文有效，当你的TextView要显示中文的时辰要在code中设置粗体的paint来实现，如下

TextView title = new TextView（context）;TextPaint paint = title.getPaint（）;  
 paint.setFakeBoldText（true）; 

还有从xml中得到，但是这样麻烦在我项目中有很多次，我必须设置一个ID然后去找到，然后再去用代码设置它的大小，所以我想了一个一劳用逸的方法，那就是自定view，但我也不知道自定view怎么弄，所以有如下：

在贴出代码之前首先就view的重点说一下：

1.  如果含有自己独特的属性，那么就需要在构造函数中获取属性文件attrs.xml中自定义属性的名称 并根据需要设定默认值，

2. 如果使用自定义属性，那么在应用xml文件中需要加上新的schemas， 

比如这里 xmlns:my="[http://schemas.android.com/apk/res/demo.dedo](http://schemas.android.com/apk/res/deme.deme)"，

3. 其中xmlns后的“my”是自定义的属性的前缀，res后的是我们自定义View所在的包

4.特别注意，因为我在我编写的时候，老是出现，找不到资源什么什么的，我看了一下，“自定义View所在的包”必须和AndroidManifest中的 package="deme.deme"相同。

 

现在贴出代码

1.attrs.xml

```
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="TestView">
         <attr name="textblod" format="integer" />
     </declare-styleable>
</resources>
```

 

2.TestView

```
package demo.dedo;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;
public class TestView extends TextView
{
 private TextPaint paint;
 private Context mContext;
 public TestView(Context context, AttributeSet attrs)
 {
  super(context, attrs);
  // TODO Auto-generated constructor stub
  mContext = context;
  // 对于我们自定义的类中，我们需要使用一个名为obtainStyledAttributes的方法来获取我们的定义
  TypedArray params = mContext.obtainStyledAttributes(attrs,
    R.styleable.TestView);
  // 得到自定义控件的属性值。
  int backgroundId = params.getInteger(R.styleable.TestView_textblod, 0);
  setTextblod(backgroundId);
 }
 public void setTextblod(int textblod)
 {
  if (textblod == 1)
  {
   paint = super.getPaint();
   paint.setFakeBoldText(true);
  }
 }
}
```

  

3.在xml中引用view

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:my="http://schemas.android.com/apk/res/demo.dedo" 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 
    <deme.deme.TestView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     my:textblod="1"
     android:text="这只是一个测试"
     />
    
 
    
</LinearLayout>
```