onTouchEvent does not work when the view is in a layout - java

I have created a class MapView that draws some circles and lines representing a map, where you can touch a circle to change the color of it. If works as it should, but when I add the View to a Layout the touchlistener does not return any touches.
Here is my MainActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.*;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
MapView mapView;
RelativeLayout mainLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainLayout = new RelativeLayout(this);
mapView = new MapView(this);
mapView.findViewById(R.id.theMap2);
mapView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
System.out.println("Touch! X: " + x + ", Y: " + y);
mapView.touched(x, y);
return true;
}
return true;
}
});
setContentView(R.layout.activity_main2);
}
I can see that the mapView works by doing this: setContentView(mapView);
Here is activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<bus.com.ece602_bus.MapView
android:id="#+id/theMap2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
What am I doing wrong? Why are the touches not registered?

setContentView(R.layout.activity_main2); creates a new layout with a new instance of MapView than the one you set the listener for.

Related

Color detection in android (java) delivers wrong RGB values

I am trying to make a program in Android Studio using java, where I can determine the RGB values at the point where the user clicked on the image. The code is working so far, but it gives wrong RGB values as output. They also seem to vary, based on the location where I click, even if the color that should be put out is the same. My guess is, that there is something up with the Bitmap, that I don't know about.
My MainActivity :
package com.example.fitme;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
switch (action) {
case MotionEvent.ACTION_DOWN :
break;
case MotionEvent.ACTION_UP :
ImageView img = (ImageView) findViewById (R.id.body_front_map);
img.setDrawingCacheEnabled(true);
Bitmap imgbmp = Bitmap.createBitmap(img.getDrawingCache());
img.setDrawingCacheEnabled(false);
int pxl = imgbmp.getPixel(evX, evY);
int redComponent = Color.red(pxl);
int greenComponent = Color.green(pxl);
int blueComponent = Color.blue(pxl);
Toast.makeText(MainActivity.this,"RED: "+redComponent+" GREEN: "+greenComponent+" BLUE: "+blueComponent, Toast.LENGTH_SHORT).show();
break;
}
return false;
}
}
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">
<ImageView
android:id="#+id/body_front_map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:background="#drawable/body_front_map"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
The Image I am trying to use

Android Studio - App crashing when trying to change a TextView properties with code when it's located at a custom xml file

Basically I am trying to change a TextView properties with coding, and this TextView is located at a custom xml that I have created called popup.xml, when I try to change the text Font, color or anything using code in MainActivity.java the App will crash with the errors:
java.lang.RuntimeException: Unable to start activity and java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Error from the TextView:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.dragoonshimizu.realtest.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Unknown Source:16)
at android.app.Activity.performCreate(Unknown Source:1)
at android.app.Instrumentation.callActivityOnCreate(Unknown Source:3)
at android.app.ActivityThread.performLaunchActivity(Unknown Source:368)
MainActivity.java (Updated by Mike M code) :
package com.example.test;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private PopupWindow popupWindow;
private LayoutInflater layoutInflater;
private RelativeLayout relativelayout;
private TextView textYouLose;
private TextView countTimeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativelayout = (RelativeLayout) findViewById(R.id.relative);
textYouLose = (TextView) findViewById(R.id.textYouLose);
View popupView = getLayoutInflater().inflate(R.layout.popup, null);
textYouLose = popupView.findViewById(R.id.textYouLose);
popupView.findViewById(R.id.popupLayout);
textYouLose.setText("ABC");
PopupWindow popup = new PopupWindow(popupView);
popup.setContentView(popupView);
startCounting();
}
public void startCounting() {
countTimeText = (TextView) findViewById(R.id.countTimeText);
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
countTimeText.setText("Time Left: " + millisUntilFinished / 1000);
}
// On Finish PopupWindow
public void onFinish() {
// textYouLose.setText("Error Here!");
countTimeText.setText("TimeUp!");
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup, null);
// Adding true will make it closable if clicked outside window
popupWindow = new PopupWindow(container, 1080, 1920, true);
popupWindow.showAtLocation(relativelayout, Gravity.NO_GRAVITY, 500, 500);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return true;
}
});
}
}.start();
}
}
popup.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="#E16A6A"
android:id="#+id/popupLayout"
android:orientation="vertical">
<TextView
android:id="#+id/textYouLose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layoutDirection="rtl"
android:text="You lose!"
android:textAlignment="center"
android:textSize="40dp" />
</RelativeLayout>
Currently the app doesn't crash with the updated code, but neither it changes the text to what I have set it to "ABC".
The inflated view activity_main.xml does not contain any Textview with #+id/textYouLose.
Just copy/paste your texview code in your activity_main.xml :
<TextView
android:id="#+id/textYouLose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layoutDirection="rtl"
android:text="You lose!"
android:textAlignment="center"
android:textSize="40dp" />

Draggable image Android Studio

Im super new and have slowly been working on an app. ive kinda hit a road block when ive tried to make an image moveable by pressing it and dragging it. I used this as my inital reference.
http://www.devexchanges.info/2015/03/simple-moving-object-with-touch-events.html
But when I do that and run it nothing happens when i press the image to move it around. Heres what my Code looks like. I feel like it is a super simple solution. I dont have any errors in the code according to android studio.
Below is my activity_touch.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_touch"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#24d7d4"
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="com.example.daniel.movebutton.activity_touch">
<ImageView
android:id="#+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
android:contentDescription="#string/app_name"
android:src="#drawable/bunny"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here is the activity_touch.java
package com.example.daniel.movebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class activity_touch extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch);
}
}
Then this is my TouchActivity.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class TouchActivity extends Activity {
private ViewGroup mainLayout;
private ImageView image;
private int xDelta;
private int yDelta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch);
mainLayout = (RelativeLayout) findViewById(R.id.activity_touch);
image = (ImageView) findViewById(R.id.image);
image.setOnTouchListener(onTouchListener());
}
private OnTouchListener onTouchListener() {
return new OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent event) {
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
view.getLayoutParams();
xDelta = x - lParams.leftMargin;
yDelta = y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
Toast.makeText(TouchActivity.this,
"thanks for new location!", Toast.LENGTH_SHORT)
.show();
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = x - xDelta;
layoutParams.topMargin = y - yDelta;
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
view.setLayoutParams(layoutParams);
break;
}
mainLayout.invalidate();
return true;
}
};
}
}
I really feel like Im just missing something in the activity_touch.java
Any help would be great! Thanks guys!

Move Image Left & Right When it Zoomed

How to move image right to left when it zoomed ? I have done zooming on images and now don't know which codes to write for creating movement using finger once it zoomed.
Please have a look at my code and give me your precious reply. Edit my code if possible. Thanks in advance.
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ZoomControls;
public class MainActivity extends Activity {
ImageView img;
ZoomControls zoom;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imageView1);
zoom = (ZoomControls) findViewById(R.id.zoomControls1);
zoom.setOnZoomInClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int w = img.getWidth();
int h = img.getHeight();
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(w + 10, h +10);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
img.setLayoutParams(params);
}
});
zoom.setOnZoomOutClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int w = img.getWidth();
int h = img.getHeight();
RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(w - 10, h -10);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
img.setLayoutParams(params);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_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_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/ic_launcher" />
<ZoomControls
android:id="#+id/zoomControls1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp" />
Try this library..it easy to implement and works flawlessly
Image Zoom Library

Android, painting on my own, "divided" layout doesn't work

I need to create a layout, which must be divided in half, like this:
-------
| |
| A |
| |
-------
| |
| B |
| |
-------
Where:
A - this is the place, where I can draw points with a finger;
B - it is an example ListView.
It looks like no object from class SampleView was created, so painting in A doesn't work.
What's wrong with that?
How do I need to fix painting?
drawing_activity.xml:
<?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:layout_weight="1"
android:orientation="vertical" >
<View
class="com.example.proj.SampleView"
android:id="#+id/sampleView1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight=".50" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".50" >
</ListView>
</LinearLayout>
SampleView.java:
package com.example.proj;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class SampleView extends View implements OnTouchListener {
private static final String TAG = "SampleView";
List<Point> points = new ArrayList<Point>();
Paint paint = new Paint();
public SampleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
Log.i(TAG, "Created SampleView!");
}
#Override
public void onDraw(Canvas canvas) {
for (Point point : points) {
canvas.drawCircle(point.x, point.y, 5, paint);
Log.d(TAG, "Painting: "+point);
}
}
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() != MotionEvent.ACTION_DOWN)
return super.onTouchEvent(event);
Point point = new Point();
point.x = event.getX();
point.y = event.getY();
points.add(point);
invalidate();
Log.d(TAG, "point: " + point);
return true;
}
}
class Point {
float x, y;
#Override
public String toString() {
return x + ", " + y;
}
}
MainActivity.java:
package com.example.proj;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_activity);
final ListView listview = (ListView) findViewById(R.id.listView1);
String[] values = new String[] { "Element1", "Element2" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
}
}
In your xml must be:
<com.example.proj.SampleView
android:id="#+id/sampleView1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight=".50" />
OR: view with non-capitalized "V"
<view
class="com.example.proj.SampleView"
android:id="#+id/sampleView1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight=".50" />
Both tags view and View exist, however View will generate a new View class whereas view will generate from the class tag.

Categories