Hey guys i am getting to start an intent if a user clicks on specific location.at first touch he opens a menu and on second he opens the activity.The problem is that many copy's of same intent are started
import android.app.Activity;
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.Paint.Align;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
public class gfx extends Activity implements OnTouchListener{
Bitmap a,b;
gfx1 drw;
String a1;
boolean flag=false,flag1=false,flag2=false;
Canvas c1;
float x=0,y=0,z=0,bitx=0,bity=0;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
drw = new gfx1(this);
drw.setOnTouchListener(this);
setContentView(drw);
}
public class gfx1 extends View implements Runnable {
public gfx1(Context context) {
super(context);
// TODO Auto-generated constructor stub
a = BitmapFactory.decodeResource(getResources(),
R.drawable.greenball);
}
void callin(String a1)
{
Intent inte = new Intent(a1);
startActivity(inte);
}
#Override
protected void onDraw(Canvas c1) {
// TODO Auto-generated method stub
super.onDraw(c1);
c1.drawColor(Color.YELLOW);
b=Bitmap.createScaledBitmap(a,c1.getWidth()/3, c1.getHeight()/3, true);
bitx=(c1.getWidth()/2)-(a.getWidth()/2);
bity=(c1.getHeight()/2)-(a.getHeight()/2);
c1.drawBitmap(a, bitx, bity, null);
Paint textPaint = new Paint();
textPaint.setARGB(50, 254, 10, 50);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTextSize(30);
if(flag)
{
c1.drawText("clicked",300, 300,textPaint);
c1.drawBitmap(b,(c1.getWidth()/2)-(b.getWidth()/2),(c1.getHeight()/2)+(a.getHeight()/2), null);
c1.drawBitmap(b,(c1.getWidth()/2)-(b.getWidth()/2),(c1.getHeight()/2)-(a.getHeight()/2)-(b.getHeight()), null);
}
float bitbx1=(c1.getWidth()/2)-(b.getWidth()/2);
float bitbx2=(c1.getWidth()/2)+(b.getWidth()/2);
float bitby1=(c1.getHeight()/2)-(b.getHeight())-(a.getHeight()/2);
float bitby2=((c1.getHeight()/2)-(a.getHeight()/2));
if(flag2)
{
c1.drawText("Opening...please wait", 600, 600, textPaint);
flag1=true;
if(flag1)
{
a1="com.example.claci.MAINACTIVITY";
callin(a1);
}
flag1=false;
}
if((x>bitx&&x<bitx+(a.getWidth()))&& (y>bity&&y<bity+(a.getHeight())))
{
flag=true;
}
if((x>bitbx1&&x<bitbx2)&&(y>bitby1&&y<bitby2))
{
if(flag)
{
flag2=true;
}
}
invalidate();
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
x=event.getX();
y=event.getY();
break;
}
return true;
}
}
A much better structure would be to have your menu creation, and subsequent activity creation called from onTouch method. As psink mentioned, that is not the proper use of onDraw, and it unnecessarily links tow very unrelated things.
I would also use two class variables-- one that is a flag for if the menu exists yet, and another that is a reference to the newly created activity. If an activity already exists, you don't create another one. When the existent activity completes, though, it needs to return a result to this activity so you can clear that reference and be ready to create a new one when needed.
Related
I was trying to run some test on SurfaceViewer with SurfaceViewer having its own thread and everything worked just fine. Then I changed my code to change orientation of screen using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
In the code below: I have an activity which uses Fragments. I have another class which extends SurfaceView class. Problem starts when I add setRequestedOrientation. After I add setRequestedOrientation. Value of running at in FastRender Class run method is always false. If I comment line with setRequestedOrientation , it runs fines.
package com.example.testpractise;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class SurfaceViewTest extends ActionBarActivity {
static int counter;
static {
Log.i("Intializing class Surface Test","counter");
System.out.println("Statrting here");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
counter++;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
counter++;
Log.i("Counter vlase",String.valueOf(counter));
System.out.println("value of counter"+counter);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_surface_view_test);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.surface_view_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
FastRenderView renderView;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(
// R.layout.fragment_surface_view_test, container, false);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
BitmapCollection.initializeBitMapCollection(getActivity());
renderView = new FastRenderView(getActivity());
return renderView;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
renderView.resume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
renderView.pause();
}
static class FastRenderView extends SurfaceView implements Runnable {
Thread renderThread = null;
SurfaceHolder holder;
static volatile boolean running = false;
int x=0;
int y=0;
public FastRenderView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = getHolder();
}
public void pause()
{
running = false;
while(true)
{
try{
renderThread.join();
}catch (InterruptedException i){
}
}
}
public void resume()
{
running = true;
renderThread = new Thread(this);
renderThread.setName("RendererThread");
renderThread.start();
running=true;
}
#Override
public void run() {
// TODO Auto-generated method stub
int sleepCounter=0;
while(!running)
{
try {
if(sleepCounter <5)
{
sleepCounter++;
Thread.sleep(5000);
}else{
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while(running)
{
if(!holder.getSurface().isValid())
{
continue;
}
Canvas canvas=holder.lockCanvas();
canvas.drawRGB(255, 0, 0);
holder.unlockCanvasAndPost(canvas);
}
}
}
}
}
Sorry if my question doesn't match the format. This is my first time. Any pointers on what is wrong and why would be greatly appreciated.
Thanks
If you just want to lock the Activity to landscape, you can do it in Manifest by adding the android:screenOrientation="landscape" attribute to the activity element.
In DrawingTheBall class making some animation stuff..
In SUrfaceViewExample class Touchevent will be detecetd..
my problem is i am not able to link MainActivity and SurtfaceViewExample ..
no issues with DrawingTheBall..
MAIN CLASS:...
package maddy.first;
import android.app.Activity;
import android.os.Bundle;
public class Madhu1Activity extends Activity {
/** Called when the activity is first created. */
Drwwingtheball v;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v = new Drawingtheball(this);
setContentView(v);
}
}
CLASS SurfaceViewExample:
package maddy.first;
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 SurfaceViewExample extends Activity implements OnTouchListener{
OurView v;
Bitmap ball;
float x,y;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v=new OurView(this);
v.setOnTouchListener(this);
ball=BitmapFactory.decodeResource(getResources(),R.drawable.tennis_ball);
x = y = 0;
setContentView(v);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable{
Thread t;
SurfaceHolder holder;
boolean isItOk=false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder=getHolder();
}
public void run() {
// TODO Auto-generated method stub
while( isItOk ==true)
{
//drawing
if(holder.getSurface().isValid()) {
continue;
}
Canvas c=holder.lockCanvas();
c.drawARGB(255,150,150,10);
c.drawBitmap(ball, x-(ball.getWidth()), y-(ball.getHeight()), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause()
{
isItOk=false;
while(true) {
try {
t.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
break;
}
}
public void resume()
{
isItOk=true;
t=new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
Class DrawingTheBall:
package maddy.first;
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.Rect;
import android.view.View;
public class DrawingTheBall extends View {
Bitmap bball;
int x,y;
public DrawingTheBall(Context context) {
super(context);
bball=BitmapFactory.decodeResource(getResources() ,R.drawable.tennis_ball);
x = 0;
y = 0;
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Rect ourRect=new Rect();
ourRect.contains( 0, 0,canvas.getWidth(),canvas.getHeight()/2);
Paint blue=new Paint();
blue.setColor(Color.RED);
blue.setStyle(Paint.Style.FILL);
canvas.drawRect(ourRect, blue);
if(x < canvas.getWidth())
x+=10;
else
x=0;
if(y<canvas.getHeight())
y+=10;
else
y=0;
Paint p=new Paint();
canvas.drawBitmap(bball,x,y,p);
invalidate();
}
}
}
Your question is not clear. What actually do you want to link?
You want to start activity from another another?
Or you want to pass some parameter from one to another activity?
If you want to run SurfaceViewExample activity from Main activity -
This is the code -
startActivity(new Intent(this, SurfaceViewExample.class)
finish();
And AndroidManifest.xml file should be -
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="Madhu1Activity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="SurfaceViewExample"></activity>
</application>
And if you want to pass parameter from one activity to another -
This is the code -
startActivity(new Intent(this, SurfaceViewExample.class)
.putExtra("key", [value])); // if you want to pass class the class should be Serializable, otherwise you can pass value like a hash map.
//in other activity convert it to class-
<classname> obj = (<classname>)getIntent().getSerializableExtra("key");
If this are not sufficient then tell me what actually want.
Enjoy..
I think it throws some exception otherwise your layout has some error, so that it is unable to set the content view.
This is the easiest way to keep your SurfaceViewExample class as main activity follow it -
goto application AndroidManifest.xml file and then -
Application tab -> select launch activity(that is your main activity) ->
Name*(right side) -> browse(take for a while to loading activity list) - >
select SurfaceViewExample -> remove previous SurfaceViewExample activity if already added.
set a default layout in SurfaceViewExample setContentView(layout.main); // if it exists
And run your application to check it is able to show your layout.
If it can run successfully, then check out your DrawingTheBall code.
Have fun...
I have some ImageViews in my xml file. In my code section I want to move an image according to my wish. For that, I've done event.getx() and event.getY() and then use imageView.layout(). This process is not working. How can i move that image?
I think this might help:
package com.example.moveimageview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
ImageView im;
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the wrapper layout from the xml
rl = (RelativeLayout) findViewById(R.id.relative1);
//getting the ImageView from xml
im = (ImageView) findViewById(R.id.myImageView);
rl.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
// TODO Auto-generated method stub
if(e.getAction()==android.view.MotionEvent.ACTION_DOWN)
{
//sending the new coordinates to the method
//that will change the view's location
setImageViewLocation(e.getX(), e.getY());
return true;
}
return false;
}
});
}
#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, menu);
return true;
}
private void setImageViewLocation(float x, float y)
{
//setting the coordinates
im.setX(x);
im.setY(y);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
im.invalidate();//invoking the view onDraw
}
});
}
}
(Edit) If you want to your ImageView around, here's the onTouchListner code for this (Same code as before just replace the OnTouchListner with this):
rl.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent e) {
// TODO Auto-generated method stub
if(e.getAction()==android.view.MotionEvent.ACTION_DOWN)
{
//sending the new coordinates to the method
//that will change the view's location
setImageViewLocation(e.getRawX(), e.getRawY());
return true;
}
if(e.getAction()==android.view.MotionEvent.ACTION_MOVE)
{
setImageViewLocation(e.getRawX(), e.getRawY());
return true;
}
return false;
}
});
Where in this code would I put a thread delay, that will happen after the completion of onCreate(), which means also after the completion/showing of onDraw()? Afterwards I will be calling grid.clearPattern() which clears the pattern drawn on the canvas when grid.displayPattern() was called. So afterwards I will still need to be able to modify the canvas.
package com.patterns;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class PlayGame extends Activity implements View.OnTouchListener {
int size;
Grid grid;
PatternView patternview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
size = getIntent().getExtras().getInt("size");
patternview = new PatternView(this);
setContentView(patternview);
Handler pauser = new Handler();
pauser.postDelayed(new Runnable() {
public void run() {
patternview.clearDraw();
}
}, 2000);
patternview.setOnTouchListener(this);
}
public class PatternView extends View {
Paint paint = new Paint();
public PatternView(Context context){
super(context);
}
protected void clearDraw() {
Log.d("debug", "clearDraw called");
grid.clearPattern();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
grid = new Grid(size, size, getWidth(), getWidth(), canvas, paint);
grid.createPattern();
grid.displayPattern();
Log.d("debug", "lines drawn");
grid.setBoard();
Log.d("debug", "board set");
}
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
//Log.d("debug", "screen touched");
grid.screenTouch(arg1);
grid.fillActiveRectangles();
return false;
}
}
Maybe stick the call to grid.clearPattern() into an android.os.Handler? Had a similar app-pausing problem and this did the trick for me. So stick something like this at the end of onCreate() -- the 3500 is a pause in milliseconds, choose the value that you want.
Handler pauser = new Handler();
pauser.postDelayed (new Runnable() {
public void run() {
grid.clearPattern();
}
}, 3500);
Could it be like this?
grid.createPattern();
grid.displayPattern(canvas, paint);
Thread.sleep(2000);
But it will be a pain...
I have tried a lot of ways to trigger the backPressed() event when the progressDialog is displayed. But none works. If I provide progDialog.setcancelable(true); I am able to dismiss the progressDialog but still the onBackPressed() doesn't get triggered.
When ProgressDialog is active if yiou press back key to perform yopur own operations you have to set setOnCancelListener to the progressdialog.
write your logic inside onCancel() method example the whole logic that you have written in onBackPressed() event those things you have to write here.
Sample code
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class CancelProgressDialog extends Activity {
ProgressDialog myProgressDialog = null;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a very simple button */
Button b = new Button(this);
this.setContentView(b);
b.setText("Show ProgressBar...");
b.setOnClickListener(myProgressBarShower);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
System.out.println("...any key is pressed....");
if (keyCode == KeyEvent.KEYCODE_BACK)
{
System.out.println("...BackButton is pressed...");
if( (myProgressDialog!= null) && myProgressDialog.isShowing()){
myProgressDialog.dismiss();
}
}
return super.onKeyDown(keyCode, event);
}
/** OnClickListener that fakes some work to be done. */
OnClickListener myProgressBarShower = new OnClickListener() {
// #Override
public void onClick(View arg0) {
// Display an indeterminate Progress-Dialog
myProgressDialog = ProgressDialog.show(CancelProgressDialog.this,
"Please wait...", "Doing Extreme Calculations...", true);
myProgressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
System.out.println("...cancel button is pressed");
// perform your task here
}
});
myProgressDialog.setCancelable(true);
}
};
}
Thanks
Deepak