简体   繁体   English

如何在自定义视图中添加按钮?

[英]How to add a button to a custom view?

I'm going too build a painting application with some buttons. 我也将构建带有一些按钮的绘画应用程序。 Now i want to add some buttons to that. 现在我要添加一些按钮。 my code as follows. 我的代码如下。

 package com.example.drawing;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;


    public class TouchActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new SingleTouchEventView(this, null));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_touch, menu);
        return true;
    }
    }


package com.example.drawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class SingleTouchEventView extends View {
    private Paint paint = new Paint();
    private Path path = new Path();

    public SingleTouchEventView(Context context, AttributeSet attrs) {
        super(context, attrs);

        paint.setAntiAlias(true);
        paint.setStrokeWidth(6f);
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            path.moveTo(eventX, eventY);
            return true;
        case MotionEvent.ACTION_MOVE:
            path.lineTo(eventX, eventY);
            break;
        case MotionEvent.ACTION_UP:
            // nothing to do
            break;
        default:
            return false;
        }

        // Schedules a repaint.
        invalidate();
        return true;
    }
}

How can i add a button to this?. 我该如何添加一个按钮? reffered some sites and some answers to questions in Stackoverflow ( link 1 link 2 ) But couldn't find an answer. 引用了Stackoverflow中的一些站点和一些问题的答案( 链接1 链接2 ),但找不到答案。

You can add a button programmatically or your custom view can inflate an xml. 您可以通过编程方式添加按钮,或者您的自定义视图可以使xml膨胀。 You add to this xml the buttons you want and you are still able to draw on the canvas. 您将所需的按钮添加到该xml中,仍然可以在画布上绘制。

Create a class GraphicsActivity like: 创建一个类GraphicsActivity,例如:

class GraphicsActivity extends Activity {

private static final boolean TEST_PICTURE = true;
int f=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


}



@Override
public void setContentView(View view) {
    if (TEST_PICTURE) {

        if(f==0){
        ViewGroup vg = new PictureLayout(this);
        vg.addView(view);

        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View vi = inflater.inflate(R.layout.activity_main, vg);
        view = vg;
        }

    }



    super.setContentView(view);
}



/*@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
    super.onConfigurationChanged(newConfig);
    if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
        f=0;
        }else{
         f=1;


        }

}*/

} }

Create your activity_main and add necessary buttons on it. 创建您的activity_main并在其上添加必要的按钮。 The following is your PictureLayout.java : 以下是您的PictureLayout.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

    public PictureLayout(Context context) {
        super(context);
    }

    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException(
                    "PictureLayout can host only one direct child");
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException(
                    "PictureLayout can host only one direct child");
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException(
                    "PictureLayout can host only one direct child");
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException(
                    "PictureLayout can host only one direct child");
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx,
            float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth() / 2;
        int y = getHeight() / 2;

        if (true) {
            canvas.drawPicture(mPicture);
        } else {
            drawPict(canvas, 0, 0, x, y, 1, 1);
            //drawPict(canvas, x, 0, x, y, -1, 1);
            //drawPict(canvas, 0, y, x, y, 1, -1);
            //drawPict(canvas, x, y, x, y, -1, -1);
        }
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

The above procedure should work.Your class should extend GraphicsActivity instead of Activity . 上面的过程应该起作用,您的类应该扩展GraphicsActivity而不是Activity

You just needed to extend ViewGroup rather than View for your custom view to add some child to it and add button to it dynamically as 您只需要扩展ViewGroup而不是View即可为您的自定义视图添加一些子项,并以动态方式向其添加按钮

SingleTouchEventView view = new SingleTouchEventView(this, null);

Button btn = new Button(this);
LayoutParams pars = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btn.setLayoutParams(pars);
btn.setText("Hello World");
btn.setPadding(10, 10, 10, 10);
view.addView(btn);

setContentView(view);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM