How can I move an image based on a user's touch? - java

I am trying to get an image to move, either to the Left Or Right, when the user touches either the Left Or Right of their device's screen. I have the following code....I have run the Emulator, in Android Studio, and when I click on the Right or Left sides of the Emulator's Screen....nothing happens. What is wrong with this code? All answers are welcome! I have entered the following code in the Activity that has the image I want to move:
public class GameScreen1 extends AppCompatActivity implements View.OnTouchListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen1);
ImageView circle1 = (ImageView) findViewById(R.id.circle1);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.circle1:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//WHAT CODE SHOULD I PUT INSTEAD OF THE FLOAT X AND X++
int ScreenWidth = getResources().getDisplayMetrics().widthPixels;
float Xtouch = event.getRawX();
int sign = Xtouch > 0.5*ScreenWidth ? 1 : -1;
float XToMove = 50;
int durationMs = 50;
v.animate().translationXBy(sign*XToMove).setDuration(durationMs);
}
break;
}
return false;
}
}

Add ID to your root layout in the activity and add TouchListener on it.
Here's an example:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/cl_root"
android:layout_height="match_parent"
tools:context=".MainActivity">
</android.support.constraint.ConstraintLayout>
And This is the code of your activity:
public class MainActivity extends AppCompatActivity {
ConstraintLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.cl_root);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int x = (int)event.getX();
if ( x >= ( screenWidth/2) ) {
//Right touch
}else {
//Left touch
}
return false;
}
});
}
}

Related

Image dialog event

I have a question about my java code. I would like to open a image as a dialog and then pick the color of the image.
The colorpicker is working fine.
The dialog is working also.(Picture is opening in a popup)
The only problem is when i open the image in the dialog the colorpicker is not working anymore.
Please help?
The code!
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View mylayout = LayoutInflater.from(this).inflate(R.layout.activity_2,null);
final ImageView myImage = (ImageView) mylayout.findViewById(R.id.imageView1);
myImage.setDrawingCacheEnabled(true);
myImage.buildDrawingCache(true);
final Button button1 = (Button) findViewById(R.id.button1);
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//getting Hex value
String hex = "#" + Integer.toHexString(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
System.out.println("r"+r+"g"+g+"b"+b);
// Make the variable a global var easy way
} catch(Exception e){
System.out.println("FOUT JONGUH");
}
}
return true;
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_2);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
}
}
MAIN XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="427dp" />
Second XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/dirk" />
You need to declare the imageview on dialog not on layout inflater. You can do it like this;
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.activity_2);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final ImageView myImage = (ImageView) dialog.findViewById(R.id.imageView1); //here is the imageview
dialog.show();
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//getting Hex value
String hex = "#" + Integer.toHexString(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
System.out.println("r"+r+"g"+g+"b"+b);
// Make the variable a global var easy way
} catch(Exception e){
System.out.println("FOUT JONGUH");
}
}
return true;
}
});
then put your onTouchlistener inside the button.onClickListener
I fixed it by doing this!
// View mColorView;
TextView mResults;
Bitmap bitmap;
String dirk;
Boolean wait = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
mResults = findViewById(R.id.textView4);
//mColorView = findViewById(R.id.colorView);
final Dialog dialog = new Dialog(Activity2.this);
dialog.setContentView(R.layout.popupp);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
final ImageView myImage = (ImageView) dialog.findViewById(R.id.ImageView112);
myImage.setDrawingCacheEnabled(true);
myImage.buildDrawingCache(true);
Button popupje = (Button) findViewById(R.id.popupje);
final Button gereed = (Button) findViewById(R.id.Gereed);
//image view on touch listener
gereed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
wait = true;
if(wait == true) {
myImage.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
try {
bitmap = myImage.getDrawingCache();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
//getting RGB values
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
//set background color of view
//mColorView.setBackgroundColor(Color.rgb(r,g,b));
mResults.setText("RGB" + r + g + b);
// Make the variable a global var easy way
String srtlred = Integer.toString(r);
String srtlblue = Integer.toString(b);
String srtlgreen = Integer.toString(g);
System.out.println("http://192.168.68.158/?r" + srtlred + "g" + srtlgreen + "b" + srtlblue + "&");
webView.loadUrl("http://192.168.68.158/?r" + srtlred + "g" + srtlgreen + "b" + srtlblue + "&");
} catch (Exception e) {
//MEANS THAT THE USER IS GOING OUT OF THE IMAGEVIEW
}
}
return true;
}
});
}
//Makes the correct URL to send to the webview.
//tring srtlred = Integer.toString(red);
//String srtlblue = Integer.toString(blue);
//String srtlgreen = Integer.toString(green);
//System.out.println("http://192.168.68.158/?r"+srtlred +"g"+ srtlgreen+"b" +srtlblue+"&");
//webView.loadUrl("http://192.168.68.158/?r"+srtlred +"g"+ srtlgreen+"b" +srtlblue+"&");
}
});
}
}

How To Transition object on RelativeLayout Using Android Studio?

I want Transition my object called ball inside ImageView on ReltiveLayout when I touch ReltiveLayout then ball move to center of point has been touch
public class MainActivity extends AppCompatActivity {
//ImageView.W(70dp) ImageView.H(70dp) to get center touch
ImageView ball;
RelativeLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ball = (ImageView)findViewById(R.id.ball);
layout = (RelativeLayout) findViewById(R.id.layout);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
//ImageView.W(70dp) ImageView.H(70dp)
//touch X,Y-70 to move ball to center touch
ball.setX(motionEvent.getX()-70);
ball.setY(motionEvent.getY()-70);
return false;
}
});
}
}

How to implement pan and pinch zoom gesture into android GridView?

I want to make a board using android GridView as follows -
I need to make the GridView zoomable using two fingers and also pannable.
What is a standard and easy way to do this?
I'm able to make an imageview zoomable but not pannable using the following code-
public class MainActivity extends Activity {
private ImageView imageView;
private float scale = 1f;
private ScaleGestureDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
detector = new ScaleGestureDetector(this,new ScaleListener());
}
public boolean onTouchEvent(MotionEvent event) {
// re-route the Touch Events to the ScaleListener class
detector.onTouchEvent(event);
return super.onTouchEvent(event);
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
float onScaleBegin = 0;
float onScaleEnd = 0;
#Override
public boolean onScale(ScaleGestureDetector detector) {
scale *= detector.getScaleFactor();
imageView.setScaleX(scale);
imageView.setScaleY(scale);
return true;
}
#Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
Toast.makeText(getApplicationContext(),"Scale Begin" ,Toast.LENGTH_SHORT).show();
onScaleBegin = scale;
return true;
}
#Override
public void onScaleEnd(ScaleGestureDetector detector) {
Toast.makeText(getApplicationContext(),"Scale Ended",Toast.LENGTH_SHORT).show();
onScaleEnd = scale;
if (onScaleEnd > onScaleBegin){
Toast.makeText(getApplicationContext(),"Scaled Up by a factor of " + String.valueOf( onScaleEnd / onScaleBegin ), Toast.LENGTH_SHORT ).show();
}
if (onScaleEnd < onScaleBegin){
Toast.makeText(getApplicationContext(),"Scaled Down by a factor of " + String.valueOf( onScaleBegin / onScaleEnd ), Toast.LENGTH_SHORT ).show();
}
super.onScaleEnd(detector);
}
}
}
I tried by replacing the imageview part with gridview in this code. But that didn't work.How do I implement this properly?

Nothing getting drawn

This code shows nothing on my screen when run. I need to draw a simple circle wherever you touch.
public class Touchevent extends AppCompatActivity {
float mLastTouchX = 0;
float mLastTouchY = 0;
Canvas zex=new Canvas();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touchevent);
RelativeLayout mylayout = (RelativeLayout)findViewById(R.id.test);
mylayout.setOnTouchListener(
new RelativeLayout.OnTouchListener() {
public boolean onTouch(View v, MotionEvent m) {
onTouchEvent(m);
onDraw(zex);
return true;
}
}
);
}
public void onDraw(Canvas canvasx) {
canvasx.drawColor(Color.WHITE);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvasx.drawCircle(mLastTouchX,mLastTouchY,100,paint);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
mLastTouchX = ev.getX();
mLastTouchY = ev.getY();
return true;
}
}
The code shows no error. Do I need to add a custom view? Then how to implement a click listener?

Example of how to change textView Color onTouch?

been working on a prject for a while, now I want it so that when the user touches the screen it changes the color of the textView(DigitalClock). I'm a bit of a noob when it comes to java so I really need a fully working example if possible? Here's my code so far:
public class MainActivity extends Activity {
private static final Random RANDOM = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Handler handler = new RandomMoveHandler((TextView) findViewById(R.id.digitalClock1));
handler.sendEmptyMessage(0);
}
private static class RandomMoveHandler extends Handler {
private final WeakReference<TextView> textViewWeakReference;
private RandomMoveHandler(TextView textView) {
this.textViewWeakReference = new WeakReference<TextView>(textView);
}
#Override
public void handleMessage(Message msg) {
TextView textView = textViewWeakReference.get();
if (textView == null) {
Log.i(TAG, "WeakReference is gone so giving up.");
return;
}
int x = RANDOM.nextInt(670 - 100);
int y = RANDOM.nextInt(1230 - 100);
Log.i(TAG, String.format("Moving text view to (%d, %d)", x, y));
textView.setX(x);
textView.setY(y);
//change the text position here
this.sendEmptyMessageDelayed(0, 30000);
}
}
textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// use any of your own colors here...
textView.setTextColor(android.R.color.holo_purple);
return true;
}
});
See also https://developer.android.com/reference/android/widget/TextView.html#setTextColor(int)

Categories