接下来继续研究我们的自定义组件。
有自定义组件< 二> 可以看出declear-styleable这个Android自己给我们提供的属性标识很重要。declare-styleable的主要作用是给自定义控件添加自定义属性时用的。
比如定义一个attr.xml问价件:
<declare-styleable name="mygridview">
<attr name="titles" format="reference|string" />
<attr name="title_iv" format="reference"/>
<attr name="return_icon" format="reference"/>
<attr name="setting_icon" format="reference"/>
</declare-styleable>
其中,format类型在上篇章节中已经提到:当format="dimension"/>来说,其属性的名称为"myTextSize",format指定了该属性类型为dimension,只能表示字体的大小。
format还可以指定其他的类型比如;
reference 表示引用,参考某一资源ID string 表示字符串 color 表示颜色值
dimension 表示尺寸boolean 表示布尔值 integer 表示整型值 float 表示浮点值 fraction 表示百分数 enum 表示枚举值 flag 表示位运算
例如:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="lyTextView">
- <attr name="fontSize" format="dimension" />
- </declare-styleable>
- </resources>
我们只需要在xml布局中引入我们的自定义类即包名.类名。
<包名.类名>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</包名.类名>
其中,attr.xml怎样引入呢,其是就是so easy的事了。
其中有2中方法可以用。实质上也是一种方式。即:
lyTextView:fontSize = "40dp" lyTextView:font Size = "textsize = 40dp"
由此可以看出,我们所自定义的属性的引用类似于系统 的一样,即android :fontSize = "";
因为系统的也是人写出来的罢了,只是大牛写出来集成到官方网上去,供我们使用而已。比葫芦画瓢谁不会?
另外:只要你在布局中引入之后:例如:
public class MyGridView extends GridView{
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setGirdView();
}
private void setGirdView() {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
setLayoutParams(params);
setNumColumns(3);// 设置每行列数
setGravity(Gravity.CENTER);// 位置居中
setVerticalSpacing(1);// 垂直间隔
setHorizontalSpacing(1);// 水平间隔
setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
setBackgroundColor(getResources().getColor(R.color.color));
WindowManager windowManager = ((Activity)mContext).getWindowManager();
Display display = windowManager.getDefaultDisplay();
int left = dip2px(mContext, 10);
int width_grid = display.getWidth()-2*left;
int i = width_grid / 7;
int j = width_grid - (i * 7);
int x = j / 2;
setColumnWidth(dip2px(mContext, i+x));
//setPadding(dip2px(mContext, 1), 0,dip2px(mContext, 1), 0);// 居中
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- -->
<com.example.customgridviewdemo.view.MyGridView
android:id="@+id/application_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
在引入我们的自定义组件之后,自动的调用构造方法,并可以调用构造方法里的我们所定义的普通方法。
比如setGirdView();就一样。
你当然也可以设置其他属性,这里我做的是自定义GridView,可以在构造方法里面添加所有用自定义属性的方法。
你还可以重写其onMeasure();使其重新计算其大小。这是要根据需要加入其要重写的几个方法。
在以后的讲解中我专门会给大家讲解如何自定义GridView。来实现项目中所需要的格子布局。
老于始终坚信:
没有做不到的,只有想不到了。