-1
我想要做的是將自定義視圖添加到我的活動中,並隨意將其拖放到我想要的任何位置。我創建了一個新的類「Square」。當我構造一個新的Square時,它顯示在顯示屏的左上角。當我設置X和Y座標時,它會消失。如果我將X和Y設置爲30,我會發現Square是單獨顯示的。因此,我的視圖似乎只顯示在顯示屏左上角的一個小框架中。
請幫我移動我的自定義視圖或顯示。謝謝!自定義視圖只顯示在左上角
MainActivity:
private Button btnNewSquare;
private RelativeLayout relativeLayout;
private Square[] square = new Square[10];
int squareId = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNewSquare = (Button)findViewById(R.id.button1);
relativeLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);
btnNewSquare.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == btnNewSquare) {
squareId++;
square[squareId] = new Square(this);
square[squareId].setX(30);
square[squareId].setY(30);
square[squareId].setOnTouchListener(square[squareId]);
relativeLayout.addView(square[squareId]);
relativeLayout.invalidate();
Toast.makeText(getApplication(), "Square" + squareId, Toast.LENGTH_SHORT).show();
square[squareId].invalidate();
}
}
廣場
private int squareWidth = 100;
private Paint paint;
public Square(Context context) {
super(context);
initSquare();
// TODO Auto-generated constructor stub
}
public Square(Context context, AttributeSet attrs) {
super(context, attrs);
initSquare();
}
private final void initSquare() {
paint = new Paint();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(squareWidth, squareWidth);
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
paint.setStyle(Style.FILL);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(getX(), getY(), getX() + squareWidth, getY() + squareWidth, paint);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
v.setVisibility(View.VISIBLE);
}
return false;
}
我的XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/RelativeLayout"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:text="New Square" />
</RelativeLayout>
我進一步調查。它與拖放無關。我在創建我的廣場時將X和Y設置爲30,僅繪製了partilly。看起來應用程序左上角有一些面具,方塊只顯示在那裏。 – AlexS