How to use my own view in an Android layout? - android

I have created one view, view code is,
public class MyDraw extends View{
//List<Point> mArryLstpoints = new ArrayList<Point>();
Paint paint =new Paint();
Paint mPaintAlphabet = new Paint();
public MyDraw(Context context) {
super(context);
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
// TODO Auto-generated constructor stub
}
public MyDraw(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
mPaintAlphabet.setDither(true);
mPaintAlphabet.setColor(0xFFFF0000);
mPaintAlphabet.setStyle(Paint.Style.STROKE);
mPaintAlphabet.setStrokeJoin(Paint.Join.ROUND);
mPaintAlphabet.setStrokeCap(Paint.Cap.ROUND);
mPaintAlphabet.setStrokeWidth(3);
mPaintAlphabet.setTextSize(400);
}
public void onDraw(Canvas canvas){
canvas.drawColor(Color.GRAY);
canvas.drawText("A",100,350, mPaintAlphabet);
System.out.println("in on draw");
for(Point mPoint:MyAlphabetsActivity.mArryLstpoints)
canvas.drawCircle(mPoint.x, mPoint.y, 12, paint);
}
}
I want use this view in layout and I want to set background images for the view. I am using following code,
<?xml version="1.0" encoding="utf-8"?>
<com.qteq.myalphabets.MyDraw
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" ></com.qteq.myalphabets.MyDraw>
My activity class is,
public class MyAlphabetsActivity extends Activity {
/** Called when the activity is first created. */
MyDraw mMyDraw;
Button mBtnOk;
AttributeSet attributeSet;
public static List<Point> mArryLstpoints = new ArrayList<Point>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
* WindowManager.LayoutParams.FLAG_FULLSCREEN);
*/
/*
* mMyDraw=new MyDraw(this); setContentView(mMyDraw);
* mMyDraw.requestFocus();
*/
mMyDraw = (MyDraw) findViewById(R.id.mMyDraw_layout);
mMyDraw.bringToFront();
mMyDraw.requestFocus();
mMyDraw.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Point mPoint=new Point();
mPoint.x=event.getX();
mPoint.y=event.getY();
System.out.println("in on touch");
mArryLstpoints.add(mPoint);
System.out.println("Array list is-----"+mArryLstpoints);
setContentView(R.layout.main);
return true;
}
});
// setContentView(R.layout.main);
}
}
class Point{
public float srtx;
float x, y;
#Override
public String toString() {
System.out.println("in on point");
return x + ", " + y;
}
}
and Displaying and onTouch Method called only one time.

You are Adding view with fill_parent width and height , so no space to add other views like buttons and images .
one of the possible implementation
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.qteq.myalphabets.MyDraw
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_contentt" ></com.qteq.myalphabets.MyDraw>
<Button/>
<ImageView/>
</LinearLayout>
Dont forget to add constructor
public MyDraw(Context context, AttributeSet attributeSet) {
super(context, ttributeSet);
in MyDraw.java
******** *editing* ******
in onTouch()
return super(v, event) instead of true ;
also check if you need to write setOnTouchListener() to view or canvas .

You can place your view within a layout in your XML and there can be other elements, as well, within that layout. You can set layout background to something, too.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/mybackground">
<com.qteq.myalphabets.MyDraw
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>

Related

Custom View is only displayed on the upper left corner

what I want to do is to add a custom view to my activity and freely drag and drop it wherever I want to. I create a new class "Square". When I construct a new Square it is displayed in the upper left Corner of the Display. When I set X and Y coordinates it disappears. If I set X and Y to 30 I see that the Square is displayed partiatelly. So it seems that my view is only displayed in a small Frame on the top Left of the Display.
Please help me to move my custom view oder the Display. Thanks!
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();
}
}
Square
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;
}
My 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>
The answer is simple. The coordinates in the onDraw() method are belonging to the view, not to the Screen. So if I move my view via Drag and Drop to let's say (500, 500) I have to draw my rectangle in the onDraw method still at (0,0,100,100) and not at (500, 500, 600, 600) so the correct line of code would be:
canvas.drawRect(0, 0, squareWidth, squareWidth, paint);
and not
canvas.drawRect(getX(), getY(), getX() + squareWidth, getY() + squareWidth, paint);

Execute the code inside onDraw() only after the click in view

I have a class that extends a view.
This class is called in xml to build my view. Now the view call the onDraw automatically the onDraw function on loaded. But how i can do what is do on onDraw() function only after i click in that view?? In conclusion i need to execute the code inside onDraw() only after the click in view.
DrawView.java:
public class DrawView extends View {
Paint mPaint = new Paint();
Context context;
public DrawView(Context context, AttributeSet attrs){
super(context, attrs);
this.context = context;
// setWillNotDraw(true);
}
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
mPaint.setColor(Color.MAGENTA);
canvas.drawRect((float) (getWidth()*0.3), (float) (getHeight()*0.3), getWidth(), getHeight(), mPaint);
main.xml:
<LinearLayout
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="0dip"
android:layout_weight="1">
<com.example.sliding.DrawView
android:id="#+id/tv_listRow_item1"
android:tag="tv_listRow_item1_1"
android:layout_height="0dip"
android:layout_width="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:width="100dip"
android:height="30dip"
android:background="#drawable/textview_listrow_border"/>
</LinearLayout>
main.java:
((DrawView)v.findViewById(R.id.tv_listRow_item1)).setOnClickListener(listener);
private View.OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
}
}
Any suggestions? Thanks for your time and attention.
Try overriding the
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// your actions here
}
}
then call invalidate() function, which will set a flag to call the onDraw() of your view.

How to stack a canvas and a button?

I want to write the following application. There is a Canvas
and a Button stacked vertically in a LinearView. When the button
is pressed the first time a circle is drawn in the canvas, then
if pressed again the circle disappears. The circle must appear
centered in its space.
Any ideas?
Thanks,
JG
This should work
Custom View class
public class DrawView extends View {
private Canvas viewCanvas;
public DrawView(Context context) {
super(context);
setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT
,LinearLayout.LayoutParams.FILL_PARENT));
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p = new Paint();
p.setColor(Color.RED);
canvas.drawCricle(getWidth()/2,getHeight()/2,50,null);
viewCanvas = canvas;
}
public clearCircle(){
viewCanvas.drawColor(Color.BLACK);
}
}
Activity class should look like this
public class KeyboardTopDemo extends Activity {
private FrameLayout container;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ss);
container = (FrameLayout)findViewById(R.id.sc);
container.addView(new DrawView(this));
}
public void clearHandler(View target){
container.getChildAt(0).clearCircle();
}
}
This is the layout xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<FrameLayout android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="0dip" android:id="#+id/sc"
android:scrollbars="horizontal" android:layout_weight="1.0">
<ImageView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:src="#drawable/chips"/>
</FrameLayout>
<Button android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Clear" android:onClick="clearHandler"/>
</LinearLayout>

It is possible to set the text of a "TextView" from within a class 'extends View'

I've insert a custom View called "disegno" inside a Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?windowsBackground">
<it.package.myapp.Disegno
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/finestraDisegno"
android:isScrollContainer="true" />
<FrameLayout
android:layout_height="0dp"
android:layout_width="0dp"
...
<EditText
...
android:id="#+id/et_MOD_x">
</EditText>
Then I've implemented the extends View class for populate the custom layout:
package it.package.myapp;
import android.content.Context;
...
public class Disegno extends View {
public Disegno(Context context) {
this(context, null, 0); }
public Disegno(Context context, AttributeSet attrs) {
this(context, attrs, 0);
setContentView(R.layout.main); }
public Disegno(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
init(attrs); }
...
#Override
protected void onDraw(Canvas canvas) {
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
// chiamo routine assi cartesiani
AssiCartesiani(canvas);
// chiamo routine polilinea
Polilinea(canvas); }
...
Now I would to set the text of the textView "et_MOD_x" by "findViewById(R.Id.et_MOD_x)" changing the code like this:
#Override
protected void onDraw(Canvas canvas) {
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
canvas.translate(mPosX, mPosY);
canvas.scale(mScaleFactor, mScaleFactor);
// chiamo routine assi cartesiani
AssiCartesiani(canvas);
// chiamo routine polilinea
Polilinea(canvas);
EditText et_MOD_x = (EditText) findViewById(R.Id.et_MOD_x)
et_MOD_x.setText("abcd");
}
but without "setContentView(...)" is not possible!
Summing: I would to set the text of a "EditText" from within an "extends View" class. I'd to pointing to an external layout... mmmhh!
There is any way to do this?!
have a reference in your custom view
public class Disegno extends View {
private TextView textView;
public void setTextView(TextView tv){
textview = tv;
}
#Override
protected void onDraw(Canvas canvas) {
textview.setText("Your text here!")
}
}
in your Activity.onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.my_layout);
EditText et_MOD_x = (EditText) findViewById(R.Id.et_MOD_x);
Disegno finestraDisegno = (Disegno)findViewById(R.Id.finestraDisegno);
finestraDisegno.setTextView(et_MOD_x) ;
}
May be this is not the right way but you can :
Get your editText in your activity and declare it as static.
public static EditText et_MOD_x;
et_MOD_x = (EditText) findViewById(R.Id.et_MOD_x)
and In your View class set the text by :
YourActivity.et_MOD_x.setText("abcd");
Hope it helps..

Android: How to add button and a custom view

I use the following View to draw a bitmap and move it around.
public class DrawView extends View {
private ColorBall ball;
public DrawView(Context context) {
super(context);
setFocusable(true);
ball = new ColorBall(context,R.drawable.bol_groen, points);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null);
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// do stuff...
}
}
In the starting Activity, the layout is set using setContentView(new DrawView(this));
I want add a button to the screen and when I click on the button, I want a new bitmap to be added. How do I add a button to this screen?
EDIT: This is my main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button android:text="Button"
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<com.example.DrawView
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Set activity's layout from xml. Put there button and your custom view (you can make it GONE if you don't want it to be visible).
But before making it you should have one more constructor for your view
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
ball = new ColorBall(context,R.drawable.bol_groen, points);
}

Categories

Resources