很多时候系统自带的View满足不了设计的要求,就需要自定义View控件。自定义View首先要实现一个继承自View的类。添加类的构造方法,override父类的方法,如onDraw,(onMeasure)等。如果自定义的View有自己的属性,需要在values下建立attrs.xml文件,在其中定义属性,同时代码也要做修改。
一个简单的例子:
·新建一个MyView类,继承自TextView,并添加构造方法:
package com.example.xhelloworld; import android.content.Context; import android.widget.TextView; public class MyView extends TextView{ public MyView(Context context) { super(context); // TODO Auto-generated constructor stub } }
·再在主activity中调用。方法是setContentView(new MyView(this));
package com.example.xhelloworld; import android.app.Activity; import android.os.Bundle; import android.view.Menu; public class NewView extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_newview); setContentView(new MyView(this)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_newview, menu); return true; } }
运行后的结果为:
这样一个简单的自定义View就可以使用了。可以改变一下背景颜色,在MyView类中添加:
@Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.drawColor(Color.BLUE); }
即可完成。运行结果