简体   繁体   中英

Add a button to a custom view in Android

Here is my main_activity.xml file:

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="barnquilt.nkc.com.barnquiltmaker.MainActivity">

    <view
        android:layout_width="500dp"
        android:layout_height="500dp"
        class="barnquilt.nkc.com.barnquiltmaker.Qulits.MainDrawingView"
        android:id="@+id/single_touch_view"
        android:background="#ffffff"
        />

I would like to add a button in the view tag so that the onClick goes to my MainDrawingView class not the MainActivity class.

I have tried this:

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="barnquilt.nkc.com.barnquiltmaker.MainActivity">

    <view
        android:layout_width="500dp"
        android:layout_height="500dp"
        class="barnquilt.nkc.com.barnquiltmaker.Qulits.MainDrawingView"
        android:id="@+id/single_touch_view"
        android:background="#ffffff"

        <Button
         <!--
          Add layout width and layout height here
          -->
         android:text = "test"
         android:onClick = "changeColor"
        />
        />




</RelativeLayout>

It says that the method changeColor is not defined in MainActivity. How would I make it so then it goes to my MainDraingView class instead? Thanks! Here is the MainDrawingView class:

package barnquilt.nkc.com.barnquiltmaker.Qulits;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import barnquilt.nkc.com.barnquiltmaker.BitMap.blue;
import barnquilt.nkc.com.barnquiltmaker.BitMap.red;
import barnquilt.nkc.com.barnquiltmaker.R;

/**
 * Created by pokem on 6/1/2017.
 */

//The 2 * 2 barn quilt
public class MainDrawingView extends View {

    public float eventX;
    public float eventY;

   public List<Point>redPointList = new ArrayList<Point>();
    public List<Point>bluePointList = new ArrayList<Point>();

    public Point redPoint = new Point();
    public Point bluePoint  = new Point();



    Context context = getContext();
   //Bitmaps
   public Bitmap redSquare;
   public Bitmap blueSquare;

   //Colors
   public boolean red = false;
   public boolean blue = false;
   //Squares

    public int width = context.getResources().getDisplayMetrics().widthPixels;
    public int height = context.getResources().getDisplayMetrics().heightPixels;
    public int center  = height/2;
    public int widthDiv = width/2;


    private Paint redPaint  = new Paint();
    private Paint bluePaint = new Paint();
    private Paint black = new Paint();
    private Point pointStart  = new Point();
    private Point pointEnd =  new Point();

    public MainDrawingView(Context context, AttributeSet attrs){
        super(context, attrs);
        redPaint.setAntiAlias(true);
        redPaint.setStrokeWidth(5f);
        redPaint.setColor(Color.RED);
        redPaint.setStyle(Paint.Style.STROKE);
        redPaint.setStrokeJoin(Paint.Join.ROUND);


        bluePaint.setAntiAlias(true);
        bluePaint.setStrokeWidth(5f);
        bluePaint.setColor(Color.BLUE);
        bluePaint.setStyle(Paint.Style.STROKE);
        bluePaint.setStrokeJoin(Paint.Join.ROUND);


        black.setAntiAlias(true);
        black.setStrokeWidth(5f);
        black.setColor(Color.BLACK);
        black.setStyle(Paint.Style.STROKE);
        black.setStrokeJoin(Paint.Join.ROUND);




        //define bitmap
        redSquare = BitmapFactory.decodeResource(getResources(), R.drawable.red);
        blueSquare = BitmapFactory.decodeResource(getResources(), R.drawable.blue);


    }

    @Override
    public void onDraw(Canvas canvas){

        //canvas.drawPath(path, paint);
       canvas.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y,black);
       //Makes a straight line go through the center of the screen.
       canvas.drawLine(0,height/2.5f, width,height/2.5f,black);
       //Makes a straight line go up and down.
        canvas.drawLine(width/2.3f,0, width/2.3f, height,black);

         //if(red){
             for(Point point : redPointList){
                new red(redSquare,canvas,point.x, point.y);

             }
         //}
        //if(blue){
            for(Point pointt : bluePointList){
                  new blue(blueSquare,canvas,pointt.x, pointt.y);
            }
        //}







    }

    @Override
    public boolean onTouchEvent(final MotionEvent event){
        //Gets the coords of the tap

        redPoint.x = (int)  event.getX();
        redPoint.y = (int)  event.getY();



        bluePoint.x = (int) event.getX();
        bluePoint.y = (int)event.getY();

         eventX = event.getX();
         eventY = event.getY();




        int pointX = Math.round(eventX);
        int pointY = Math.round(eventY);





            //Shows the popup dialog when the user touches the screen
            AlertDialog.Builder alertThing = new AlertDialog.Builder(getContext());
            alertThing.setTitle("edit square");
            alertThing.setMessage("please choose an option");
            alertThing.setPositiveButton("red", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {









                    red = true;
                    blue = false;
                    invalidate();

                }
            });
            alertThing.setNeutralButton("Chnange color to blue", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {


                    bluePointList.add(bluePoint);



                    blue = true;
                    red = false;
                   invalidate();
                }
            });

            alertThing.create();
            alertThing.show();











        switch(event.getAction()){

            case MotionEvent.ACTION_DOWN:
                //Sets a new starting point
             pointStart.set(pointX,pointY);



               return true;

            case MotionEvent.ACTION_UP:
                //Contects the points
              pointEnd.set(pointX,pointY);
                break;




            default:
                return false;
        }
        invalidate();
        return true;
    }







}

You can do it this way:

make your MainDrawingView extend ViewGroup , not View and implement View.onClickListener

public class MainDrawingView extends ViewGroup implements View.onClickListener

Override onClick in MainDrawingView @Override public void onClick(View v) { //do stuff }

Create a Button in MainActivity and add it to your

Button button = new Button(context);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
                               LayoutParams.WRAP_CONTENT)); 

gameView.addView(button);

set onClickListener on the button

button.setOnClickListener(new MainDrawingView());

you can handle button's click events in MainDrawingView 's onClick method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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