最も簡単な方法をレイアウトの外側のViewGroupとして既に使用しているので、FrameLayoutを拡張することです。
この作業を行うには、さらに2つのコンストラクターを宣言する必要があります。 XMLで要素を宣言すると、標準コンストラクタは使用されません。したがって、これらのコンストラクタの3つすべてでペイントを設定する必要があります。冗長性を減らすために、私はこれをprivateメソッド 'initiatePaint()'に移しました。
'setDirection'の新しい場所がわかっている場合、関数 'declarePath()'を呼び出す必要があります。
public class DrawLayout extends FrameLayout {
Paint mPaint = new Paint();
float mX1 = 0;
float mY1 = 0;
float mX2 = 0;
float mY2 = 0;
public DrawLayout(Context context) {
super(context);
this.initiatePaint();
}
public DrawLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.initiatePaint();
}
public DrawLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.initiatePaint();
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(x1, y1, x2, y2, paint);
}
public void declarePath(float x1, float y1, float x2, float y2) {
this.mX1 = x1;
this.mY1 = y1;
this.mX2 = x2;
this.mY2 = y2;
this.invalidate();
}
private void initiatePaint() {
this.mPaint.setColor(Color.BLUE);
this.mPaint.setStrokeWidth(10);
this.mPaint.setStyle(Paint.Style.STROKE);
}
}
レイアウトで使用するには、FrameLayoutの代わりに使用してください。あなたの活動に
<com.example.DrawLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fl"
tools:context="it.uniroma3.sensorlog">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/mappa"
android:id="@+id/map"/>
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:src="@android:drawable/ic_notification_overlay"
android:id="@+id/dot" />
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:visibility="invisible"
android:src="@android:drawable/ic_notification_overlay"
android:id="@+id/setDirection" />
</DrawLayout>
、あなたが何かをしなければならない。
@Override
protected void onCreate(Bundle savedInstanceState) {
[...]
this.mBackground = (DrawLayout) findViewById(R.id.fl);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
final float eventX = event.getRawX();
final float eventY = event.getRawY();
if(dotEnabled){
dot.setX(eventX);
dot.setY(eventY);
}
if(directionSet){
direction.setX(eventX);
direction.setY(eventY);
}
this.mBackground.declarePath(**Here you have to pass the coordinates of your points**);
return false;
}
を使用すると、移動イベントのための 'キャンバス' とリスナーを必要とする、ようです。 – EarlGrey
これまでに何を試しましたか?コードがありますか? – EarlGrey
@EarlGrey私はCanvasについての情報を読んでいましたが、それをどのように使用するかを知ることができませんでした。私は自分の活動の中で私のドットのxとyを持っていたので、私はこのクラスを実装しようとしました(私の投稿を編集しました..)しかし、これはビューです..どのように私の活動でこのクラスを使うことができます –