我想在android活动的xml布局中画线,我用的代码是,
public class MainActivity extends Activity {
DrawView drawView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
drawView = new DrawView(this);
setContentView(R.layout.activity_main);
drawView.requestFocus();
}
}
public class DrawView extends View implements OnTouchListener{
List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();
public DrawView(Context context){
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
paint.setColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas) {
Path path = new Path();
boolean first = true;
for(Point point : points){
if(first){
first = false;
path.moveTo(point.x, point.y);
}
else{
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() != MotionEvent.ACTION_UP){
Point point = new Point();
point.x = event.getX();
point.y = event.getY();
points.add(point);
invalidate();
Log.d(TAG, "point: " + point);
return true;
}
return super.onTouchEvent(event);
}
class Point {
float x, y;
float dx, dy;
@Override
public String toString(){
return x + ", " + y;
}
}
}
使用上面的代码我无法绘制线条。 以编程方式在XML或绘图线中使用视图的最佳方法是什么?
答案 0 :(得分:1)
您可以使用视图在xml文件中绘制线条
<View android:id="@+id/hline"
android:background="#ff005d"
android:layout_width="fill_parent"
android:layout_height="1dip"
/>