Switch between activities in Android? - android

I want to switch between my Main Actvity and my second Activity, but whenever I do it the app shuts down.
So after i click the button1 "Neues Feld", the App should switch to the second activity: feldlayout.class with the layout: feldlayout.xml! The activities are liested in the Android_MAnifest, that's also not the problem...
Thank you for the help! It's working now! I made a new View class, added it to the layout and then it worked fine!
Main Class
package com.example.volleyballapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class Main_Layout extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_layout);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(myhandler);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main__layout, menu);
return true;
}
View.OnClickListener myhandler = new View.OnClickListener(){
public void onClick(View v) {
if(v==b1){
Intent i = new Intent(Main_Layout.this, feldlayout.class);
startActivity(i);
}
}
};}
Main Layout
<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:background="#drawable/background2"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".Main_Layout" >
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:text=" "
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/farbe" />
<Button
android:id="#+id/button1"
style="#style/ButtonText"
android:layout_below="#id/textView"
android:layout_centerHorizontal="true"
android:background="#drawable/bnt_black"
android:onClick="NeuesFeldClick"
android:text="Neues Feld" />
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" "
android:id="#+id/textView2"
android:textColor="#color/farbe"
android:layout_below="#id/button1"/>
<Button
android:id="#+id/button2"
style="#style/ButtonText"
android:layout_below="#id/textView2"
android:layout_centerHorizontal="true"
android:background="#drawable/bnt_black"
android:onClick="LetztesFeldClick"
android:text="Letztes Feld" />
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" "
android:id="#+id/textView3"
android:textColor="#color/farbe"
android:layout_below="#id/button2"/>
<Button
android:id="#+id/button3"
style="#style/ButtonText"
android:layout_below="#id/textView3"
android:layout_centerHorizontal="true"
android:background="#drawable/bnt_black"
android:onClick="SavesClick"
android:text="Gespeicherte Felder" />
</RelativeLayout>
Second Activity
package com.example.volleyballapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
public class feldlayout extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feldlayout);
}
private Paint paint = new Paint();
private Path path = new Path();
int count = 1;
public feldlayout(Context context, AttributeSet attrs) {
super();
paint.setAntiAlias(true);
paint.setStrokeWidth(6f); //Breite des Strichs
paint.setColor(Color.BLACK); //Farbe des Strichs
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
protected void onDraw(Canvas canvas) {
if ((count%2 != 0)){
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:
count++;
if(count%2 != 1){
path.moveTo(eventX, eventY);
return true;
}
if(count%2 != 0){
path.lineTo(eventX, eventY);
break;
}
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
private void invalidate() {
// TODO Auto-generated method stub
}
}

It's just i tried. your code is working. The problem is you call Constructor in the second Activity. Below one.
public feldlayout(Context context, AttributeSet attrs) {
super();
paint.setAntiAlias(true);
paint.setStrokeWidth(6f); //Breite des Strichs
paint.setColor(Color.BLACK); //Farbe des Strichs
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
Please remove this constructor and try again.
Note
Just create a separate class and call the constructor there.

Related

How can I implement a View in my Activity?

I have the Feldlayout class, the feldlayout.xml which is the layout of the Feldlayout class, and I have a View class, which can be used to make lines on the screen. I want now to make these lines on the feldlayout.xml layout, but I don't know how to connect my classes. So how can I do this?
Feldlayout.class (Main Class)
package com.example.volleyballapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class feldlayout extends Activity{
Button b7;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feldlayout);
b7 = (Button) findViewById(R.id.button7);
b7.setOnClickListener(handler);
}
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
if(v==b7){
Intent i = new Intent(feldlayout.this, Main_Layout.class);
startActivity(i);
}
}};}
Feldlayout.xml (Main Layout)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/farbe"
android:orientation="vertical" >
<ImageView
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="70dp"
android:layout_marginLeft="70dp"
android:layout_marginRight="70dp"
android:layout_marginTop="160dp"
android:background="#drawable/whiterectangle" />
<ImageView
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="74dp"
android:layout_marginLeft="74dp"
android:layout_marginRight="74dp"
android:layout_marginTop="164dp"
android:background="#drawable/volleyballfeld" />
<ImageView
android:id="#+id/view3meterlinie"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_alignTop="#+id/view1"
android:layout_marginLeft="70dp"
android:layout_marginRight="70dp"
android:layout_marginTop="100dp"
android:background="#drawable/dreimeterlinie" />
<ImageView
android:id="#+id/netz"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_alignTop="#+id/view1"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="310dp"
android:background="#drawable/netz" />
<ImageView
android:id="#+id/view3meterliniedef"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_alignTop="#+id/view1"
android:layout_marginLeft="70dp"
android:layout_marginRight="70dp"
android:layout_marginTop="520dp"
android:background="#drawable/dreimeterlinie" />
<Button
android:id="#+id/button8"
style="#style/HomeText"
android:layout_width="140dp"
android:layout_height="85dp"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/view1"
android:layout_marginTop="1dp"
android:background="#drawable/bnt_black"
android:text="Speichern" />
<Button
android:id="#+id/button7"
style="#style/HomeText"
android:layout_width="140dp"
android:layout_height="85dp"
android:layout_alignLeft="#+id/view2"
android:layout_alignParentTop="true"
android:layout_marginTop="1dp"
android:background="#drawable/bnt_black"
android:onClick="home"
android:text="Zurück" />
<Button
android:id="#+id/button9"
style="#style/HomeText"
android:layout_width="140dp"
android:layout_height="85dp"
android:layout_alignTop="#+id/button7"
android:layout_marginLeft="35dp"
android:layout_toRightOf="#+id/button7"
android:background="#drawable/bnt_black"
android:text="Linien Anzeigen" />
<Button
android:id="#+id/Statistik"
style="#style/HomeText"
android:layout_width="140dp"
android:layout_height="85dp"
android:layout_alignBaseline="#+id/button8"
android:layout_alignBottom="#+id/button8"
android:layout_marginRight="31dp"
android:layout_toLeftOf="#+id/button8"
android:background="#drawable/bnt_black"
android:text="Statistik" />
</RelativeLayout>
ViewFeld.class (View class, which makes lines)
package com.example.volleyballapp;
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 ViewFeld extends View{
private Paint paint = new Paint();
private Path path = new Path();
int count = 1;
public ViewFeld(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
paint.setAntiAlias(true);
paint.setStrokeWidth(6f); //Breite des Strichs
paint.setColor(Color.BLACK); //Farbe des Strichs
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
protected void onDraw(Canvas canvas) {
if ((count%2 != 0)){
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:
count++;
if(count%2 != 1){
path.moveTo(eventX, eventY);
return true;
}
if(count%2 != 0){
path.lineTo(eventX, eventY);
break;
}
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
You can use your custom view in your layout xml:
<com.example.volleyballapp.ViewFeld
android:layout_width="....."
android:layout_height="....."
etc..... />

Couldn't click on buttons when child view is added?

When I use child view then the buttons which are in the root view are disabled. I could not click on them.
I am trying to develop application in which input is made by connecting buttons with lines. If user wants to enter
some thing then he have to touch buttons by connecting them with lines. It is very similar to android pattern
unlock. But in our application in place of dots of grid, numbers will be shown.
activity_demo_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rty"
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=".DemoMainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="222.08203dp"
android:layout_marginTop="270.53426dp"
android:text="1" />
<Button
android:id="#+id/button2"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="162.08203dp"
android:layout_marginTop="314.12678dp"
android:text="2" />
<Button
android:id="#+id/button3"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="87.917960dp"
android:layout_marginTop="314.12678dp"
android:text="3" />
<Button
android:id="#+id/button4"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="27.917960dp"
android:layout_marginTop="270.53423dp"
android:text="4" />
</RelativeLayout>
DemoMainActivity.java :
package com.example.demo;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
public class DemoMainActivity extends Activity {
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_main);
rl = (RelativeLayout)findViewById(R.id.rty);
Button b1=(Button)findViewById(R.id.button2);
final NewPattern b = new NewPattern(this);
b1.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View arg0) {
try{
rl.getRootView();
rl.addView(b);
}
catch(Exception ex){}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.demo_main, menu);
return true;
}
}
NewPattern.java:
package com.example.demo;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
//import com.example.newpattern.PatternMainActivity;
import android.widget.RelativeLayout;
public class NewPattern extends View
{
private Paint m_paint;
private static Bitmap m_bitmap;
private Canvas m_canvas;
private Path m_path;
private Paint m_bitmapPaint;
private DisplayMetrics m_metrics;
private int m_color = 0xFFFF0000;
static boolean m_pathDrawn = false;
private float m_X, m_Y;
private static final float TOUCH_TOLERANCE = 4;
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.rty);
#SuppressLint("NewApi")
private void touchman(float g, float h){
final float btn1x = b1.getX();
//float btn2x= b1.getY();
if(g==btn1x){
rl.getRootView();
}
}
public NewPattern(Context context, AttributeSet attrs) {
super(context, attrs);
//Your code
// btn1.setText("fdsf");
}
public NewPattern(Context p_c)
{
super(p_c);
try{
m_paint = new Paint();
m_paint.setAntiAlias(true);
m_paint.setDither(true);
m_paint.setColor(m_color);
/*new ColorPickerDialog(p_c, new OnColorChangedListener()
{
public void colorChanged(int p_color)
{
m_paint.setColor(p_color);
m_color = p_color;
}
}, 0xFFFF0000).show();*/
m_paint.setStyle(Paint.Style.STROKE);
m_paint.setStrokeJoin(Paint.Join.ROUND);
m_paint.setStrokeCap(Paint.Cap.ROUND);
m_paint.setStrokeWidth(12);
m_metrics = p_c.getResources().getDisplayMetrics();
m_bitmap =
Bitmap.createBitmap(m_metrics.widthPixels, m_metrics.heightPixels,
Bitmap.Config.ARGB_8888);
m_canvas = new Canvas(m_bitmap);
m_path = new Path();
m_bitmapPaint = new Paint(Paint.DITHER_FLAG);
}
catch(Exception ex){}}
public void onerase()
{
m_canvas = null;
}
#Override
protected void onSizeChanged(int p_w, int p_h, int p_oldw, int p_oldh)
{
super.onSizeChanged(p_w, p_h, p_oldw, p_oldh);
}
#Override
protected void onDraw(Canvas p_canvas)
{try{
p_canvas.drawColor(0x00000000);
p_canvas.drawBitmap(m_bitmap, 0, 0, m_bitmapPaint);
p_canvas.drawPath(m_path, m_paint);}
catch(Exception ex){}
}
#SuppressLint("NewApi")
private void touch_start(float p_x, float p_y)
{//try{
m_path.reset();
m_path.moveTo(p_x, p_y);
m_X = p_x;
m_Y = p_y;
//}
//catch(Exception ex){}
}
private void touch_move(float p_x, float p_y)
{try{
float m_dx = Math.abs(p_x - m_X);
float m_dy = Math.abs(p_y - m_Y);
if (m_dx >= TOUCH_TOLERANCE || m_dy >= TOUCH_TOLERANCE)
{
m_path.quadTo(m_X, m_Y, (p_x + m_X) / 2, (p_y + m_Y) / 2);
m_X = p_x;
m_Y = p_y;
m_pathDrawn = true;
}}
catch(Exception ex){}
}
private void touch_up()
{try{
m_path.lineTo(m_X, m_Y);
// commit the path to our offscreen
m_canvas.drawPath(m_path, m_paint);
// kill this so we don't double draw
m_path.reset();
}
catch(Exception ex){}
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent p_event)
{try{
float m_x = p_event.getX();
float m_y = p_event.getY();
switch (p_event.getAction())
{
case MotionEvent.ACTION_DOWN:
touch_start(m_x, m_y);
//touchman(m_x, m_y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(m_x, m_y);
// touchman(m_x, m_y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
//touchman(m_x, m_y);
invalidate();
break;
}
return true;
}
catch(Exception ex){}
return true;
}}

how to clear view in android?

I have created a simple demo application in android for drawing ,now can any one say me how can i remove view and clear screen in just one click .I have tried as below:please help me to do it....thanx in advance..!
main.java
package com.example.singletouch;
import com.example.singletouch.R.attr;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
ImageView pen;
SingleTouchView mDrawView;
ImageView remove;
LinearLayout pens;
LinearLayout pen1, pen2, pen3, pen4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawView = (SingleTouchView) findViewById(R.id.myview);
pen = (ImageView) findViewById(R.id.pen);
pens = (LinearLayout) findViewById(R.id.linear);
pens.setVisibility(View.GONE);
pen1 = (LinearLayout) findViewById(R.id.pen1);
pen2 = (LinearLayout) findViewById(R.id.pen2);
pen3 = (LinearLayout) findViewById(R.id.pen3);
pen4 = (LinearLayout) findViewById(R.id.pen4);
remove=(ImageView)findViewById(R.id.remove);
/*
* pen1.setOnClickListener(this); pen2.setOnClickListener(this);
* pen3.setOnClickListener(this); pen4.setOnClickListener(this);
*/
pen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pens.setVisibility(View.VISIBLE);
}
});pens.setVisibility(View.GONE);
pen1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mDrawView.setPen(SingleTouchView.DrawingPens.PEN_1);
pens.setVisibility(View.GONE);
}
});
pen2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mDrawView.setPen(SingleTouchView.DrawingPens.PEN_2);
pens.setVisibility(View.GONE);
}
});
pen3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pens.setVisibility(View.GONE);
mDrawView.setPen(SingleTouchView.DrawingPens.PEN_3);
}
});
pen4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pens.setVisibility(View.GONE);
mDrawView.setPen(SingleTouchView.DrawingPens.PEN_4);
}
});
remove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
SingleTouchView.java
package com.example.singletouch;
import java.util.AbstractMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import android.R.color;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
public class SingleTouchView extends View{
public int width;
public int height;
public Bitmap mBitmap;
public Canvas mCanvas;
public Path mPath;
public Paint mBitmapPaint;
Context context;
public Paint circlePaint;
public Path circlePath;
public enum DrawingPens {
PEN_1(6),
PEN_2(4),
PEN_3(2),
PEN_4(1);
final public Paint mPaint;
/**
* Constructor
*
* #param width width of stroke
* #param color color of stroke
*/
private DrawingPens(final int width) {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(width);
//mPaint.setColor(color);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
}
/**
* #return corresponding paint
*/
Paint getPaint() {
return mPaint;
}
}
public SingleTouchView(final Context context) {
super(context);
init(context);
}
public SingleTouchView(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SingleTouchView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
init(context);
}
/** To store Paint - Path relation */
// TODO: depending on exact limits, more optimal ways can be found
private ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>> mPaths = new ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>>();
/** Cached current path, <b>NOTE:</b> this field is tail at mPaths and is used it only for caching, not drawing */
private Path mCurrentPath;
/**
* Inits internal views data, should be called from every constructor
*
* #param context {#link Context}
*/
private void init(final Context context) {
/* TODO: if some values of paints cannot be determined in static context (in enum),
then Paints should be created here and used via EnumMap */
// Initial pen
setPen(DrawingPens.PEN_1);
}
#Override
public void onDraw(Canvas canvas){
// just to draw background
super.onDraw(canvas);
// Draw all paths
for (Map.Entry<Path, DrawingPens> entry : mPaths) {
canvas.drawPath(entry.getKey(), entry.getValue().getPaint());
}
}
#Override
public boolean onTouchEvent(MotionEvent me){
float eventX = me.getX();
float eventY = me.getY();
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN:
mCurrentPath.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
mCurrentPath.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
break;
}
invalidate();
return true;
}
/**
* Setter for new pen
*
* #param pen {#link DrawingPens} to be used for next drawing
*/
public void setPen(final DrawingPens pen) {
// put latest item to the queue
mCurrentPath = new Path();
mPaths.add(new AbstractMap.SimpleImmutableEntry<Path, DrawingPens>(mCurrentPath, pen));
}
public void clear(View v){
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<com.example.singletouch.SingleTouchView
android:id="#+id/myview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/pen" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/menubar"
android:padding="2dp"
android:weightSum="4" >
<ImageView
android:id="#+id/pen"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:gravity="center"
android:src="#drawable/pen" />
<ImageView
android:id="#+id/eraser"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:src="#drawable/eraser" />
<ImageView
android:id="#+id/color"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:src="#drawable/color" />
<ImageView
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_weight="1"
android:src="#drawable/remove" />
</LinearLayout>
<LinearLayout
android:id="#+id/linear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_alignParentLeft="true"
android:background="#eeeeee"
android:orientation="horizontal"
android:visibility="gone"
android:weightSum="4" >
<LinearLayout
android:id="#+id/pen1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/pen1" />
</LinearLayout>
<LinearLayout
android:id="#+id/pen2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/pen2" />
</LinearLayout>
<LinearLayout
android:id="#+id/pen3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/pen3" />
</LinearLayout>
<LinearLayout
android:id="#+id/pen4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/pen4" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Jus use ...
mCanvas.drawColor(Color.BLACK);
... for clearing the canvas or any other color you want to have in background. E.g.
remove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// clear canvas contents
mCanvas.drawColor(Color.BLACK);
// create new path list; old one will be garbage collected
ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>> mPaths =
new ConcurrentLinkedQueue<Map.Entry<Path, DrawingPens>>();
pens.setVisibility(View.VISIBLE);
}
p.s.: for removing a view dynamically from its container use removeView(....), e.g.
((ViewGroup)viewToRemove.getParent()).removeView(viewToRemove);
Hope this helps ... Cheers!
remove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
layout.removeView(mDrawView);
mDrawView = new SingleTouchView(MainActivity.this);
layout.addView(mDrawView);
}
});
Put the portion of the screen you want cleared in a single layout in xml eg
<RelativeLayout
android:id="#+id/layout"
android:layout_width="wrap_content"
android:layout_height= "wrap_content">
The Views that have to be gone on click
</RelativeLayout>
Then in your code in onClick() of the button give
((RelativeLayout) findViewById(R.id.layout)).setVisiblity(View.GONE));
EDIT :
If you want the ImageView cleared use :
((ImageView) findViewById(R.id.imageView)).setImageDrawable(null);
instead of drawing solid color you can draw transparent color this help you don't cover the other views if you use them as a background for the canvas
mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
I got this from this answer: https://stackoverflow.com/a/10882301/8113211

Moving image with touch events

I need a sample code for when we move(touch) a image from left to right and right to left. Please help me.
Regards,
chakri
try this code...
this is your main activity class
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int eid = event.getAction();
switch (eid) {
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams mParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
int x = (int) event.getRawX();
int y = (int) event.getRawY();
mParams.leftMargin = x-50;
mParams.topMargin = y-50;
imageView.setLayoutParams(mParams);
break;
default:
break;
}
return true;
}
});
}
}
main.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" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="126dp"
android:layout_marginTop="168dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>

How to Draw something with your finger in an Android App.... And save it to the web

**THIS QUESTION WAS SUCCESSFULLY ANSWERED AND HAS BECOME A BLOG POST <- click **
Hi I am a PHP developer I want to do a simple thing - I want to draw something drawn on a blank page on an Android Phone (with a finger with a largeish "emulated pen nib") and store the bitmap as a jpeg on a server by http post.
Here is what I have so far but this is taken from a tutorial that is involved with writing sprites for a game.. And I cant' adapt it
package com.my.example;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class DrawCapture extends Activity implements OnTouchListener{
OurView v;
Bitmap ball;
float x,y;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.draw_capture);
v = new OurView(this);
v.setOnTouchListener(this);
ball = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);
x = y = 0;
setContentView(v);
}
#Override
protected void onPause(){
super.onPause();
v.pause();
}
protected void onResume(){
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOK = false;
public OurView(Context context) {
super(context);
holder = getHolder();
}
public void run() {
while (isItOK == true){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
//perform canvas drawing
if (!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
onDraw(c);
holder.unlockCanvasAndPost(c);
}
}
public void onDraw(Canvas c){
c.drawARGB(255, 210, 210, 210);
c.drawBitmap(ball, x - (ball.getWidth()/2), y - (ball.getHeight()/2), null);
}
public void pause(){
isItOK = false;
while(true){
try{
t.join();
} catch(InterruptedException e){
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOK = true;
t = new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent me){
switch (me.getAction()){
case MotionEvent.ACTION_DOWN :
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_UP :
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_MOVE :
x = me.getX();
y = me.getY();
break;
}
return true;
}
}
and here is the XML
<?xml version="1.0" encoding="utf-8"?>
<SurfaceView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</SurfaceView>
Can someone please help me? I feel I am close - I use the blueball as a pen nib I just want to "save" this and possibly I'll need to have a button (or menu) on the XML page to do this ? I know it's a bit of a beg but there are a lot of people online asking how to draw with your finger and save something to the "cloud" if people could respond with examples of the code (not references) I promise I will compile this into a proper tutorial piece of code for the eventual benefit of all. Including the PHP server side code that I already am really happy with.
You can try to use the Gesture Object proposed by Google, try to execute my following code :
Activity1 xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
<android.gesture.GestureOverlayView
android:id="#+id/gestures"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fadeEnabled="false"
android:fadeOffset="5000000000"
android:gestureColor="#000000"
android:gestureStrokeType="multiple"
android:gestureStrokeWidth="1"
android:uncertainGestureColor="#000000"
android:layout_above="#+id/save_button" />
<Button
android:id="#id/save_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20sp"
android:paddingLeft="20sp"
android:paddingRight="20sp"
android:text="Save"
android:textSize="22sp" />
</RelativeLayout>
Activity1 java :
package com.testandroidproject;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Activity1 extends Activity {
private Button button_save;
private GestureOverlayView gesture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gesture = (GestureOverlayView) findViewById(R.id.gestures);
button_save = (Button) findViewById(R.id.save_button);
button_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
Bitmap gestureImg = gesture.getGesture().toBitmap(100, 100,
8, Color.BLACK);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
gestureImg.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("draw", bArray);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Activity1.this, "No draw on the string",
3000).show();
}
}
});
}
}
Activity2 xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<ImageView
android:id="#+id/image_saved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Activity2 java :
package com.testandroidproject;
import java.io.ByteArrayInputStream;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_image);
ImageView image = (ImageView) findViewById(R.id.image_saved);
ByteArrayInputStream imageStreamClient = new ByteArrayInputStream(
getIntent().getExtras().getByteArray("draw"));
image.setImageBitmap(BitmapFactory.decodeStream(imageStreamClient));
}
}
Hope you will find this helpful.
I'm not sure what part of the "save" you are trying to accomplish, but I'll assume you're asking how to store what you've drawn on the canvas to a bitmap.
First, make yourself a bitmap to draw into. Say, canvasBitmap. Then:
c.setBitmap(canvasBitmap);
This will store everything that has been drawn into 'canvasBitmap.' Then, when the user presses a button to save:
savedBitmap = Bitmap.copy(canvasBitmap.getConfig(), true);
Now, take savedBitmap and fire it off into the cloud. Hope that helps.

Categories

Resources