How to add CustomView to Layout fromXML?

2019-07-24 05:21发布

I want to add this PaintingView() that is in this Activity from XML file.

public class Full extends Activity implements  ColorPickerDialog.OnColorChangedListener  {       
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
      setContentView(R.layout.paint);

      FrameLayout myFrameLayout = (FrameLayout) findViewById(R.id.framelayout);        
      myimage = (ImageView) findViewById(R.id.ImageView01);
      InputStream is = this.getResources().openRawResource(imageId1);
      originalBitmap = BitmapFactory.decodeStream(is);       
      myimage.setImageBitmap(originalBitmap);
      myimage.setScaleType(ScaleType.MATRIX);  

      mView = (PaintingView)findViewById(R.id.my_view);
      mView.setDrawingCacheEnabled(true);
      mView.setVisibility(View.INVISIBLE);
      final ImageButton paint = (ImageButton) findViewById(R.id.paint_button); 
         paint.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            mView.setVisibility(View.VISIBLE);
         }
      });

      mPaint = new Paint();
      mPaint.setAntiAlias(true);
      mPaint.setDither(true);
      mPaint.setColor(0xFFFF0000);
      mPaint.setStyle(Paint.Style.STROKE);
      mPaint.setStrokeJoin(Paint.Join.ROUND);
      mPaint.setStrokeCap(Paint.Cap.ROUND);
      mPaint.setStrokeWidth(4);
      mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);

//////////////******** Menu Creation *************////////////////

private static final int COLOR_MENU_ID = Menu.FIRST;
private static final int BLUR_MENU_ID = Menu.FIRST + 1;
private static final int ERASE_MENU_ID = Menu.FIRST + 2;
private static final int BRUSH_MENU_ID = Menu.FIRST + 3;

@Override 
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c');
    menu.add(0, BLUR_MENU_ID, 0, "Glow Draw").setShortcut('5', 'z');
    menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z');
    menu.add(0, BRUSH_MENU_ID, 0, "Brush").setShortcut('5', 'z');
    return true;
}

@Override 
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
       return true;
}

@Override 
public boolean onOptionsItemSelected(MenuItem item) {
    mPaint.setXfermode(null);
    mPaint.setAlpha(0xFF);

    switch (item.getItemId()) {
        case COLOR_MENU_ID:
            new ColorPickerDialog(this,this, mPaint.getColor()).show();
            return true;
        case ERASE_MENU_ID:
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            return true;
        case BLUR_MENU_ID:
            if (mPaint.getMaskFilter() != mBlur) {
                mPaint.setMaskFilter(mBlur);
            } else {
                mPaint.setMaskFilter(null);
            }
            return true;
        case BRUSH_MENU_ID:

            sizeSeekBar.setVisibility(View.VISIBLE);
          /////////*************** Stroke width changed *************//////////////
         sizeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
         @Override
         public void onProgressChanged(SeekBar seekBar,int progress, boolean fromUser) {
             strokeWidth = sizeSeekBar.getProgress();   // b == progress value.     
             mPaint.setStrokeWidth(strokeWidth);    
         }
         @Override
         public void onStartTrackingTouch(SeekBar seekBar) {    }
         @Override
         public void onStopTrackingTouch(SeekBar seekBar) {
             Context c = getBaseContext();
             Toast.makeText(c, " BrushWidth " + strokeWidth, Toast.LENGTH_SHORT).show();
             sizeSeekBar.setVisibility(View.INVISIBLE);
         }
         });
         return true;  
    }
    return super.onOptionsItemSelected(item);
}

///////  colour changed function, getting value from ColorPickerDialog   ///////
public void colorChanged(int color) {
    mPaint.setColor(color);
}

////////////******************* Pinting view *******************///////////////////

/// MY PAINTING view /////////
public class PaintingView extends View {
    int bh = originalBitmap.getHeight();
    int bw = originalBitmap.getWidth();
    public PaintingView(Context c)  {
        super(c);

        //mBitmap = Bitmap.createScaledBitmap(originalBitmap,bw,bh,true);
        mBitmap = Bitmap.createBitmap(bw,bh,Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
    }
    public PaintingView (Context c, int color)  {  
        super(c);
        mBitmap = Bitmap.createBitmap(bw,bh,Bitmap.Config.ARGB_8888);
        //mBitmap = Bitmap.createScaledBitmap(originalBitmap,bw,bh,true);
        mCanvas = new Canvas(mBitmap);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)) ;
        mCanvas.drawColor(color);
    } 
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);           
            /*mBitmap = Bitmap.createBitmap(bw, bh, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);*/
    }
    @Override 
    protected void onDraw(Canvas canvas) {   
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawPath(mPath, mPaint);
    }

    ////////************touching evants for painting**************///////
    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;
    private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }
    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;
        }
    }
    private void touch_up() {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        mPath.reset();
    }

    @Override 
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;

            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
    }  //end of touch events for image

}// end MyView  

}

Xml format is: // tried like this UnSuccess.

2条回答
混吃等死
2楼-- · 2019-07-24 06:00
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:id="@+id/relativeLayout1">

    <com.logistics.wheresTheParty.photoTab.ImageViewTouch
        android:id="@+id/imageViewTouch" android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</RelativeLayout>

Change as per your package name and classname....

查看更多
可以哭但决不认输i
3楼-- · 2019-07-24 06:12

you can add your custom view to your xml layout using

<ParentLayout>
<yourPackagePath.customviewname
//layout attributes come here
/>
</ParentLayout>

In the particular case of your question.

<pathtoyourclass.PaintingView
//layout attributes
/>
查看更多
登录 后发表回答