您的位置:首页 > 其它

自定义适应屏幕大小的TextView

2013-04-11 11:48 363 查看
先来个截图:在来看看自定义的TextView:
public class MyTextView extends TextView
{

public MyTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
float textSize = a.getDimension(R.styleable.MyTextView_myTextSize, 36);
int size = DisplayUtil.px2dip(textSize);
this.setTextSize(size);
a.recycle();

}
}
解释一下代码:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView); 这个是获取自定义属性的集合。float textSize = a.getDimension(R.styleable.MyTextView_myTextSize, 36); 这个是获取上面集合里面的某一个属性,有一个默认值,防止别人忘写.

int size = DisplayUtil.px2dip(textSize); 通过工具类把px转换成sp。


上DisplayUtil的代码:
public class DisplayUtil
{
public static int dip2px(float dipValue)
{
final float scale = MyApplication.context.getResources().getDisplayMetrics().density;
return (int) (dipValue * (scale + 0.5f));
}
public static int px2dip(float pxValue)
{
final float scale = MyApplication.context.getResources().getDisplayMetrics().density;
return (int) (pxValue / (scale + 0.5f));
}
}
配置自定义属性 需要在values下面创建一个attrs的xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyTextView">
<attr name="myTextSize" format="dimension" />
</declare-styleable>
</resources>
最后mainActivity的布局:
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mytextview="http://schemas.android.com/apk/res/com.example.mytextview"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.mytextview.MyTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
mytextview:myTextSize="45px"
android:text="我是自适应的文字" /><TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="我是普通的文字" />
</LinearLayout>
第2行很关键的
xmlns:mytextview 自己可以随意定义 下面引用要用的

com.example.mytextview 这个是自已包的名字


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: