自定义适应屏幕大小的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"第2行很关键的
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>
xmlns:mytextview 自己可以随意定义 下面引用要用的
com.example.mytextview 这个是自已包的名字
相关文章推荐
- Android 自定义TextView实现文本内容自动调整字体大小以适应TextView的大小
- Android 自定义TextView实现文本内容自动调整字体大小以适应TextView的大小
- Android 自定义TextView实现文本内容自动调整字体大小以适应TextView的大小
- 自定义TextView 可以设置drawable的大小
- 自定义TextView实现设置drawable图片大小
- 自定义View中图片不能根据屏幕大小自动创建
- 触摸控制字体大小(自定义TextView)
- 自动调整TextView字体大小以适应文字长度&拖动一个角增大textView面积
- android textview宽度固定的情况下字体大小自适应
- Android 自定义view-如何设置TextView drawableLeft 图片大小?
- Android WebView 播放视频无法播放问题和视频适应屏幕大小
- 自定义可以设置drawable大小的TextView
- 设置了背景图片的TextView,其尺寸设置为wrap_content时,并不是适应文字内容大小
- 自动调整textview字体大小以适应textview长度
- Android 自定义TextView实现文本内容自动调整字体大小
- 自定义view时使用xml传递参数-设定TextView中图片大小
- WebView 加载html图片如何适应屏幕大小
- webview网页自适应手机屏幕大小
- webview网页自适应手机屏幕大小
- 自定义 view 自定textview显示内容字体的大小颜色控件的宽高