这里主要记录下控件自定义的步骤
![]()
一、自定义控价大致分类:
·集成系统控件
·组合系统控件
·自定义绘制控件
二、添加Attribute
在res/value下新建attrs.xml文件,自定义需要声明的属性:
1 2 3
| <declare-styleable name="MarkCalendar"> <attr name="dateFormat" format="string"/> </declare-styleable>
|
然后在自定义控件中,初始化的时候进行声明:
1 2 3 4 5 6 7 8 9 10 11 12
| //声明自定义属性 TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.MarkCalendar); try { String format = ta.getString(R.styleable.MarkCalendar_dateFormat); disPlayFormat = format; if (disPlayFormat == null) { disPlayFormat = "MMM yyyy"; }
} finally { ta.recycle(); }
|
记住声明完后一定要回收 ta.recycle()。
三、添加事件
1 2 3 4 5 6
| /** * 添加点击事件 */ public interface MarkClendarListener{ void onItemLongPress(Date day); }
|
然后初始化调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public MarkClendarListener markClendarListener;
gvDays.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (markClendarListener == null) { return false; }else { markClendarListener.onItemLongPress((Date) parent.getItemAtPosition(position)); return true; } } });
|
最后activity中调用:
实现MarkClendarListener接口,并实现其方法。
1 2 3 4 5 6 7 8 9
| MarkCalendar markcalendar = findViewById(R.id.markcalendar); markcalendar.markClendarListener = this; }
@Override public void onItemLongPress(Date day) { DateFormat df = SimpleDateFormat.getDateInstance(); Toast.makeText(this,df.format(day),Toast.LENGTH_SHORT).show(); }
|
Demo链接