我想要做的是将自定义视图添加到相对布局中。该相对布局是另一个线性布局的子布局。一切正常,除了自定义视图没有显示在它应该有的地方。
自定义查看代码:
public class DrawView extends View {
private Path path = new Path();
private Paint paint = new Paint();
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(2.2f);
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eX = event.getX();
float eY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eX, eY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eX, eY);
return true;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
invalidate();
return true;
}
}
XML 布局(线性和相对):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F24738"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/draw_container"
android:layout_width="match_parent"
android:layout_height="450dp"
android:background="#FFFFFF">
</RelativeLayout>
这就是主要活动:
public class DrawActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw);
final RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.draw_container);
parentLayout.addView(new DrawView(this, null));
}
}
当我尝试:
setContentView(new DrawView(this, null));
一切正常。我被这里击中了。我知道,我错过了一些非常简单的东西。