我一直在浏览网络上的所有文档和示例,但我还没有找到任何有关使用Java构建自定义视图的好资源。我见过很多关于使用XML和Java创建它们的描述。
我认为我最挣扎的事情是相对简单的事情,比如“我可以在自定义视图中使用”TextView“小部件并使用画布绘制一些图形吗?我已经成功地做了一个或另一个但似乎无法找到同时做到这两点的方法。
例如:我希望在视图顶部有一个TextView小部件,其下方有一个可触摸的图形作为一个表盘,并绘制到画布上,一旦添加TextView,它就会占用所有可用空间。当我转动拨盘时,它会增加TextView内的文本。我认为类似下面的东西会起作用......但事实并非如此,而且很可能是因为我遗漏了一些简单的东西。
public class Dial extends LinearLayout implements View.OnTouchListener
{
Bitmap _dial;
protected int bpm = 120;
TextView txtBpm;
/**
* Constructor
* @param context
*/
public Dial(Context context)
{
super(context);
_dial = BitmapFactory.decodeResource(getResources(), R.drawable.dial_small);
txtBpm = new TextView(context);
txtBpm.setTextSize(43);
txtBpm.setWidth(100);
txtBpm.setText(String.valueOf(bpm));
this.addView(txtBpm);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
// Setting the y-pos to 160 so even
// if the canvas fills the view,
// the dial will still be below the textview.
canvas.drawBitmap(_dial, 0,160,null);
}
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH)
{
}
/* (non-Javadoc)
* @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
*/
@Override
public boolean onTouch(View arg0, MotionEvent arg1)
{
// Do some stuff here to rotate the dial
return false;
}
}