Inflater使用
把一个xml文件转换成一个view,就会需要使用到LayoutInflater。
private LayoutInflater mLayoutInflater;
获得LayoutInflater实例的三种方式:
mLayoutInflater = getLayoutInflater();
mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
mLayoutInflater = LayoutInflater.from(MainActivity.this);
把XML文件读出来,并转换成一个视图
View view = mLayoutInflater.inflate(R.layout.activity_main, null);
后面可以addContent(view)或者用findViewById在里面找控件
提取布局属性:theme & style
Theme:针对窗体,改变窗体样式
Style:针对窗体元素级别,改变指定控件,或者Layout的样式
抽象view的共同属性
可继承
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
这里是自己添加的:
<style name="CustomTextView">
<item name="android:background">@color/red</item>
<item name="android:textSize">26sp</item>
<item name="android:textColor">#f9d004</item>
</style>
继承自父类
<style name="StudyTextView" parent="CustomTextView">
<item name="android:background">@color/colorAccent</item>
<item name="android:gravity">right</item>
</style>
</resources>
<TextView
android:id="@+id/title_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/StudyTextView" 在这里应用
android:text="好好学习,天天向上"
android:textSize="@dimen/button_txt_size"
/>
View
控件和布局都是继承自view,源码将近2万行。
构造器---初始化
onMeasure
onLayout
onDraw
onFlash
自定义控件的3种主要实现形式:
1、继承已有控件
2、继承布局文件,addView
3、继承view类
自定义视图的属性
在values文件夹下新建attrs.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TestRedButton">
<attr name="backgroundColor" format="color"/>
<attr name="textColor" format="color"/>
<attr name="textSize" format="integer"/>
</declare-styleable>
</resources>
在TestRedButton.java
使用:
private int mBackgroundColor;
在init函数中:
// 获取自定义属性的所有属性所在的数组
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TestRedButton);
// 获取自定义属性,并设置如果没有获取到,则默认值为红色
mBackgroundColor = typedArray.getColor(R.styleable.TestRedButton_backgroundColor, Color.RED);
mTextSize = typedArray.getInteger(R.styleable.TestRedButton_textSize, 18);//18个像素
在onDraw中:
mPaint.setColor(mBackgroundColor);
mPaint.setTextSize(mTextSize);
在xml中使用:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" 新添加命名空间
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.jsc4.aboutactivity.TestRedButton
android:layout_width="300dp"
android:layout_height="300dp"
app:backgroundColor="@color/colorAccent"/> 使用自定义的属性
</LinearLayout>