I know its possible to create activities by doing something like the code bellow, where the view is not set from xml file but like this: setContentView(new myView(this));
What i don't understand is how to use this code but still have the ability to customize it, for instance if i wanted to add a button to the code bellow, how would i do it, because i cant simply add one to an xml layout can i?
ANY GOOD ANSWERS TO THIS WILL VERY MUCH APPRECIATED
thanks in advance!
package com.faceapp;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;
public class FaceappActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(new myView(this));
}
private class myView extends View{
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face5,
BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect(
(int)(myMidPoint.x - myEyesDistance),
(int)(myMidPoint.y - myEyesDistance),
(int)(myMidPoint.x + myEyesDistance),
(int)(myMidPoint.y + myEyesDistance),
myPaint);
}
}
}
}
^^^^^^^^^^^^^^^
Answered
How to position the button and imageview? (Ideally using relative layout)
The picture bellow shows you what i mean:
(Ignore that the image is re-sized)
NEW CODE:
package com.test;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class TesttActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button button = new Button(this);
button.setText("Button!");
layout.addView(button);
myView custom = new myView(this);
layout.addView(custom);
setContentView(layout);
}
private class myView extends View{
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face5,
BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect(
(int)(myMidPoint.x - myEyesDistance),
(int)(myMidPoint.y - myEyesDistance),
(int)(myMidPoint.x + myEyesDistance),
(int)(myMidPoint.y + myEyesDistance),
myPaint);
}
}
}
}
You can pass setContentView() any form of view, to be the root view of your layout. Below is a dynamically built LinearLayout with a Button and your myView.
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
// Define the LinearLayout's characteristics
layout.setGravity(Gravity.CENTER);
layout.setOrientation(LinearLayout.VERTICAL);
// Set generic layout parameters
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setText("Button!");
layout.addView(button, params); // Modify this
myView custom = new myView(this);
layout.addView(custom, params); // Of course, this too
setContentView(layout);
}
}
Understand that you can only add child views to your root view if you pass setContentView() a ViewGroup; like RelativeLayout, LinearLayout, etc. In other words you cannot do this:
myView custom = new myView(this);
Button button = new Button(this);
button.setText("Button!");
custom.addView(button);
// Nope! Method "addView()" does not exist for a regular View...
setContentView(custom);
Also, naming convention suggests that each word in a class name should have the first letter capitalized. So myView ought to be MyView, at a minimum it makes your code easier to read for other programmers and the compiler will highlight your class variables with the correct color.
Related
I want to set my bitmap converted image in relative layout with the help of custom view but my image not set in the center of relative layout and its not showing complete image
My relative layout where I set my bitmap image`package org.boostram.justcolor;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.flask.colorpicker.ColorPickerView;
import com.flask.colorpicker.OnColorChangedListener;
import com.flask.colorpicker.OnColorSelectedListener;
import org.boostram.justcolor.Utils.util;
import static android.R.attr.src;
public class FillPaintActivity extends Activity implements View.OnTouchListener {
private RelativeLayout dashBoard;
Paint paint;
private MyView myView;
int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new MyView(this);
setContentView(R.layout.activity_fill_paint);
ColorPickerView colorPickerView = (ColorPickerView) findViewById(R.id.color_picker_view);
// colorPickerView.setColor(Color.WHITE,true);
paint.setColor(Color.WHITE);
colorPickerView.setInitialColor(Color.WHITE, true);
colorPickerView.addOnColorChangedListener(new OnColorChangedListener() {
#Override
public void onColorChanged(int selectedColor) {
a = 1;
paint.setColor(selectedColor);
// Handle on color change
// Log.d("ColorPicker", "onColorChanged: 0x" + Integer.toHexString(selectedColor));
}
});
colorPickerView.addOnColorSelectedListener(new OnColorSelectedListener() {
#Override
public void onColorSelected(int selectedColor) {
paint.setColor(selectedColor);
// myView.changePaintColor(selectedColor);
Toast.makeText(FillPaintActivity.this, "selectedColor: " +
Integer.toHexString(selectedColor).toUpperCase(),
// Toast.LENGTH_SHORT).show();
}
});
dashBoard = (RelativeLayout) findViewById(R.id.dashBoard);
dashBoard.addView(myView);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return false;
}
public class MyView extends View {
// private Paint paint;
private Path path;
public Bitmap mBitmap;
public ProgressDialog pd;
final Point p1 = new Point();
public Canvas canvas;
public MyView(Context context) {
super(context);
paint = new Paint();
paint.setAntiAlias(true);
pd = new ProgressDialog(context);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
// paint.setStrokeWidth(5f);
// BitmapDrawable drawable = (BitmapDrawable)
context.getDrawable(R.drawable.unnamed);
// Bitmap bmp = drawable.getBitmap();
// Bitmap mBitmap = Bitmap.createScaledBitmap(bmp, 120, 120,
false);
mBitmap = BitmapFactory.decodeResource(getResources(),
util.Id).copy(Bitmap.Config.ARGB_8888, true);
//mBitmap =
Bitmap.createScaledBitmap((BitmapFactory.decodeResource(getResources(),
util.Id).copy(Bitmap.Config.ARGB_8888, true)),1500,1380,false);
this.path = new Path();
}
#Override
protected void onDraw(Canvas canvas) {
this.canvas = canvas;
// Display display = getWindowManager().getDefaultDisplay();
// int displayWidth = display.getWidth();
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(getResources(), util.Id, options);
// int width = options.outWidth;
// if (width > displayWidth)
// {
// int widthRatio = Math.round((float) width / (float)
displayWidth);
// options.inSampleSize = widthRatio;
// }
// options.inJustDecodeBounds = false;
// Bitmap scaledBitmap =
BitmapFactory.decodeResource(getResources(),util.Id , options);
canvas.drawBitmap(mBitmap,0,0 ,paint);
// mBitmap = BitmapFactory.decodeResource
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (a == 0) {
Toast.makeText(FillPaintActivity.this, "Select Any Color First",
Toast.LENGTH_SHORT).show();
}
// Toast.makeText(FillPaintActivity.this, myView.getWidth()+""+myView.getHeight(), Toast.LENGTH_LONG).show();
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
p1.x = (int) x;
p1.y = (int) y;
if (p1.x < mBitmap.getWidth() && p1.y < mBitmap.getHeight()) {
final int sourceColor = mBitmap.getPixel((int) x, (int) y);
final int targetColor = paint.getColor();
new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
invalidate();
}
// else {
// Toast.makeText(FillPaintActivity.this, "You touched outside the Image", Toast.LENGTH_SHORT).show();
// }
}
return true;
}
public void clear() {
path.reset();
invalidate();
}
public void changePaintColor(int color) {
paint.setColor(color);
}
class TheTask extends AsyncTask<Void, Integer, Void> {
Bitmap bmp;
Point pt;
int replacementColor, targetColor;
public TheTask(Bitmap bm, Point p, int sc, int tc) {
this.bmp = bm;
this.pt = p;
this.replacementColor = tc;
this.targetColor = sc;
}
#Override
protected void onPreExecute() {
// pd.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
FloodFill floodFill = new FloodFill(bmp, targetColor, replacementColor);
floodFill.floodFill(pt.x, pt.y);
return null;
}
#Override
protected void onPostExecute(Void result) {
invalidate();
}
}
}
}
https://i.stack.imgur.com/AHpcb.png
My bitmap converted image not set in center of relative layout through view. Kindly help me i'm stuck here for almost two week. Help
I read the article on http://www.curious-creature.org/2013/12/21/android-recipe-4-path-tracing/
Trying to draw arrows with Path which mentioned in the article, but with the following code, I got the half arrow, I already read articles about how to draw arrows on android. This question is more about "what's wrong with the following code." Thanks in advance.
package com.example.linepractice;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PracticeLineView pl = new PracticeLineView(this);
LayoutInflater mInflater = LayoutInflater.from(this);
LinearLayout mainView = (LinearLayout) mInflater.inflate(R.layout.activity_main, null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(120, 120, 120, 120);
pl.setLayoutParams(params);
mainView.addView(pl);
setContentView(mainView);
}
}
package com.example.linepractice;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
public class PracticeLineView extends View {
private Paint mPaint;
public PracticeLineView(Context context) {
super(context);
mPaint = new Paint();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(getPaddingLeft(), getPaddingTop() - getPaddingBottom());
canvas.drawPath(makeArrow(140,140), mPaint);
}
private static Path makeArrow(float length, float height) {
Path p = new Path();
p.moveTo(-2.0f, -height / 2.0f);
p.lineTo(length, 0.0f);
p.lineTo(-2.0f, height / 2.0f);
p.lineTo(-2.0f, -height / 2.0f);
p.close();
return p;
}
}
pic:
private static Path makeArrow(float length, float height) {
Path p = new Path();
p.moveTo(-2.0f, 0.0f);
p.lineTo(length, height / 2.0f);
p.lineTo(-2.0f, height);
p.lineTo(-2.0f, 0.0f);
p.close();
return p;
}
If I want to add a button in this class so that I can call the onclicklistener, how should I do it?i have also provided the activity class onto which i am adding this view.
activity:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.content.Context;
public class NewGame extends Activity {
View view;
Context context;
RelativeLayout layout;
GameView gameview;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gameview=new GameView(this);
setContentView(gameview);
//layout = (RelativeLayout) findViewById(R.id.relative_layout);
//layout.addView(gameview);
}
}
view:
public class GameView extends View {
Path circle;
Paint cPaint;
Paint tPaint;
String z;
int i = 65, strt, arc, leftx, topy, rightx, bottomy, maxx, maxy;
boolean flag1, flag2, flag3;
double n1, n2;
int n, n3 = 180,n4,n5 = 90;
float f1 = 180, f2 = 90;
Button b1;
Random r = new Random();
RectF oval;
public GameView(Context context) {
super(context);
leftx = 0;
topy = 60;
rightx = 150;
bottomy = 120;
z = String.valueOf(Character.toChars(i));
cPaint = new Paint();
cPaint.setColor(Color.RED);
strt = 45;
arc = 315;
n1 = Math.random() * 600;
Log.d("random", z);
if (flag2 == false)
new DrawThread(this);
// cPaint.setStrokeWidth(2);
tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
tPaint.setColor(Color.BLACK);
float scale = getResources().getDisplayMetrics().scaledDensity;
tPaint.setTextSize(20 * scale);
}
public void onSizeChanged(int w,int h,int oldh,int oldw) {
maxx = oldw;
maxy = oldh;
}
//#Override
protected void onDraw(Canvas canvas) {
// Drawing commands go here
oval = new RectF(leftx,topy,rightx,bottomy);
canvas.drawArc(oval, strt, arc, true, cPaint);
while (i < 90) {
canvas.drawText(String.valueOf(Character.toChars(i)),f1,f2, tPaint);
break;
}
}
}
You can do it like this:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
And then you can do this
bt.setOnClickListener(new View.OnClickListener() {
//TO DO
}
I hope that this can help you.
first of all in order to allow to your custom view to have an addView(View v) method it must extend ViewGroup instead of View; then you can use this code
b1=new Button(context);
b1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT ));
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
this.addView(b1);
I am making an Android game which uses the View class and I am not using an XML-layout.
All my images are drawn with canvas. Now my problem is the I cannot use a bitmap.
I am trying to add an ImageView dynamically to my View class, to use the touchable event.
Why dynamically? Because I could not use XML-layout.
Here is my code:
package com.example.poolmaster;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private int cuePosx, cuePosy;
int cueHeight, cueWeight;
double rotatingAngle;
int height;
int wwidth;
int cueHeight2, cueWeight2;
Bitmap table, stick, raise;
ImageView button = new ImageView(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rotatingAngle = 0;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
height = displaymetrics.heightPixels;
wwidth = displaymetrics.widthPixels;
cueHeight2 = height / 2;
cueWeight2 = wwidth / 2;
System.out.println("**************************************");
System.out.println("height " + height);
System.out.println("weight" + wwidth);
System.out.println("**************************************");
// Set generic layout parameters
GamePlay custom = new GamePlay(this);
setContentView(custom);
// setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_MOVE){
// cuePosy += 10;
// System.out.println("xCORDİNATES!!!! " +ev.getX());
// System.out.println("yCORDİNATES!!!! " +ev.getY());
rotatingAngle=getAngle(ev.getX(), ev.getY());
System.out.println("Angle " +rotatingAngle);
}
if (ev.getAction()==MotionEvent.ACTION_DOWN){
System.out.println("****************** ACTİON DOWN ****************");
// cueHeight2 += 10;
// cueWeight2 += 20;
// cuePosy = 320;
}
if (ev.getAction()==MotionEvent.ACTION_UP){
System.out.println("****************** ACTİON DOWN ****************");
// cueHeight2 -= 10;
// cueWeight2 -= 20;
// cuePosy = 320;
}
return true;
}
private double getAngle(double xTouch, double yTouch) {
double theta;
theta = Math.toDegrees(Math.atan2(height / 2 - yTouch, xTouch - wwidth / 2));
return theta;
}
public class GamePlay extends View {
public GamePlay(Context context) {
super(context);
// TODO Auto-generated constructor stub
table = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
table = Bitmap.createScaledBitmap(table, wwidth, height, true);
stick = BitmapFactory.decodeResource(getResources(), R.drawable.stick);
raise = BitmapFactory.decodeResource(getResources(), R.drawable.raise);
cueHeight = stick.getHeight();
System.out.println("ıstaka " + cueHeight);
cueWeight = stick.getWidth();
cuePosx = wwidth / 2;
cuePosy = height - cueHeight - 180;
}
#SuppressLint({ "DrawAllocation", "DrawAllocation" })
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Matrix matrix = new Matrix();
matrix.setTranslate(cueWeight2, cueHeight2);
matrix.postRotate((float)rotatingAngle, cueWeight2, cueHeight2); // anti-clockwise by 90 degrees
// create a new bitmap from the original using the matrix to transform the result
Bitmap rotatedBitmap = Bitmap.createBitmap(stick, 0, 0, stick.getWidth(), stick.getHeight(), matrix, false);
canvas.save(); // Save the position of the canvas.
canvas.restore();
// Rotate the canvas.
canvas.drawBitmap(table, 0, 0, null); // Draw the ball on the rotated canvas.
canvas.drawBitmap(stick, matrix, null);
canvas.drawBitmap(raise, 0, 0, null);
invalidate();
}
}
}
This is for adding imageview to a layout where Activity class is extended
LinearLayout lL = findViewById(R.id.xmlfile_layout_id);
ImageView imgView = new ImageView(context);
imgView.setVisibility(View.VISIBLE);
lL.addView(imgView);
This is for adding imageview to a canvas where View class is extended
Initially, you cannot place any imageview, edit text or buttons using canvas. Instead, you have to draw it. So create a custom layout and draw that layout with canvas
Try this, It might help you. in onDraw(..)
LinearLayout lL = new LinearLayout(context);
ImageView imgView = new ImageView(context);
imgView.setVisibility(View.VISIBLE);
lL.addView(imgView);
lL.measure(canvas.getWidth(), canvas.getHeight());
lL.layout(0, 0, canvas.getWidth(), canvas.getHeight());
// placing the edit text at specific co-ordinates:
//canvas.translate(0, 0);
layout.draw(canvas);
And take a look at this another example : Click here
It gives another way of adding views
Use below code for that.
For Create ImageView Dynamically
ImageView mImgView1 = new ImageView(this);
For Add into your View write below code before setContentView(custom); (If GamePlay is your View Class)
custom.add(mImgView1);
I am new to Android. When i run this code, only one circle is displayed. If i remove view1, then view2 is displayed. but they are never displayed together!!! why is that?
Any help would be appreciated.
thanks
package com.dots;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Dots1Activity extends Activity
{
private static final String TAG = "DotsActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
TextView label = new TextView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
label.setText("Click the circle!");
CustomDrawableView view1 = new CustomDrawableView(this, 100, 100, 50, Color.RED);
CustomDrawableView view2 = new CustomDrawableView(this, 200, 200, 25, Color.GREEN);
CustomDrawableView view3 = new CustomDrawableView(this, 300, 300, 10, Color.WHITE);
ll.addView(label, layoutParams);
ll.addView(view1, layoutParams);
ll.addView(view2, layoutParams);
ll.addView(view3, layoutParams);
setContentView(ll);
}
}
class CustomDrawableView extends View implements OnClickListener{
private Context context;
private int x, y, radius, color;
public CustomDrawableView(Context context, int x, int y, int radius, int color) {
super(context);
this.context = context;
this.x = x;
this.y =y;
this.radius = radius;
this.color = color;
setOnClickListener(this);
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
this.setBackgroundColor(Color.LTGRAY);
Paint paint = new Paint (Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
canvas.drawCircle(x, y, radius, paint);
}
public void onClick(View v) {
Toast.makeText(this.context,
x+"-"+y+"-"+radius,
Toast.LENGTH_SHORT).show();
}
}
ll.setOrientation(LinearLayout.HORIZONTAL);
They are put next to each other. You can't see them, because your display isn't width naught. Put them in a HorizontalScrollView or make them aper VERTICAL.
I'm not sure if this takes effect here, but i found this on the Android Documentation:
Note that the framework will not draw
views that are not in the invalid
region. To force a view to draw, call
invalidate().
Try if this solves your problem (for the moment I guess).
About your Code
Something i noticed: The implemented interface for the onClickListener is View.OnClickListener:
class CustomDrawableView extends View implements View.OnClickListener{ [...] }
How to solve the Problem
I looked around on the Android Docs and found this. They mantioned the method onMeasure(), which:
Measure the view and its content to
determine the measured width and the
measured height.
So I added it to your custom CustomDrawableView-class. Unfortuandly, you can't pass the super.onMeasure()-method simple integers, you'll need to decode them first, using the View.MeasureSpec-class:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
}
In the Example, I set both width and height to 100px. Also, I did some other improvements on your code:
Dots1Activity-class
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Dots1Activity extends Activity
{
private static final String TAG = "DotsActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView label = new TextView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
label.setText("Click the circle!");
CustomDrawableView view1 = new CustomDrawableView(this, 50, 50, 50, Color.RED);
CustomDrawableView view2 = new CustomDrawableView(this, 75, 75, 25, Color.GREEN);
CustomDrawableView view3 = new CustomDrawableView(this, 85, 85, 10, Color.WHITE);
ll.addView(label, layoutParams);
ll.addView(view1, layoutParams);
ll.addView(view2, layoutParams);
ll.addView(view3, layoutParams);
setContentView(ll);
}
}
CustomDrawableView-class
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
import android.widget.Toast;
class CustomDrawableView extends View implements View.OnClickListener{
private Context context;
private int x, y, radius, color;
public CustomDrawableView(Context context, int x, int y, int radius, int color) {
super(context);
this.context = context;
this.x = x;
this.y =y;
this.radius = radius;
this.color = color;
setOnClickListener(this);
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
canvas.drawCircle(x, y, radius, paint);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY));
}
public void onClick(View v) {
Toast.makeText(this.context,
x+"-"+y+"-"+radius,
Toast.LENGTH_SHORT).show();
}
}
This code compiles, shows all the circles and the onClick-Event works, too.
Although I have to say it was a bit of a challenge and I'm grateful for it.
change the orientation of you layout to vertical like this :
ll.setOrientation(LinearLayout.VERTICAL);