Get X and Y coordinates onClick
you may should look this, that may help you:
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
Log.i("222","X-"+x+"===Y="+y);
}
return false;
}
how to get click position in onClickListener?
Use an onTouchListener with ACTION_DOWN flag
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
}
return true;
}
});
Android: custom view onClickEvent with X & Y locations
Now, I don't know about onTouchEvent short circuiting onClick, and I don't know if maybe you need to set android:clickable
to true (or setClickable(true)
). But, if you can't make it work cleanly, you can use a boolean in the onTouchEvent to mimic click detection if all else fails. in ACTION_DOWN, set it to true (isClicking or something like that), in ACTION_MOVE set it to false (because the user is dragging therefore not clicking) and then in ACTION_UP you can test for it. If it's true, this means the user has pressed down but not dragged. It's hacky, but if you can't get onClick to work it's basically the same thing.
Wrong x and y cordinates on 'onclick' event
your js seems fine, it's the css that's tripping you up :)
use position: relative on the #plants div, and position:absolute on the .plants. then rather than positioning them using margins, use top and left to supply coordinates.
explanation: position: absolute 'lifts' an element out of the normal ordering of elements on a page and positions it on x/y coordinates relative to the nearest parent with relative positioning. since you want the plants to appear in a specific area, give that relative positioning, and position the plants absolutely within that relative container.
Sorry, I didn't come up with the names of the position attributes.
see https://www.w3schools.com/css/css_positioning.asp
[edit: replaced my abbreviated html with the original entire thing.]
window.Plant = class Plant {
/**
* @param {Object} state? Custom state [optional].
*/
constructor(state) {
this.state = state || { color: 'red', colorIndex: 0, waterable: true, watered: false };
}
/**
* Changes the plant's state.
* @param {Object} state Custom state.
* @returns {Object}
*/
setState(state) {
this.state = (state ?? this.state) ?? { color: 'red', colorIndex: 0, waterable: true, watered: false };
return this.state;
}
/**
* Returns the plant's state
* @returns {Object}
*/
getState() {
return this.state ?? { color: 'red', colorIndex: 0, waterable: true, watered: false }
}
/**
* Stringify the plant's state.
* @returns {String}
*/
toString() {
return JSON.stringify(this.state);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
body {
margin: 0;
padding: 0;
background-color: #27293F;
}
#title {
width: 100vw;
height: 20vh;
}
h1 {
width: 100%;
color: #4FFF5A;
text-align: center;
}
p {
width: 100vw;
color: #379A3D;
text-align: center;
}
#plants {
position: relative;
width: 100vw;
height: 75vh;
border: 10px solid #FF5555;
display: flex;
flex-wrap: wrap;
}
.plant {
position: absolute;
width: 50px;
height: 50px;
}
</style>
<script src="Plant.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<section id="title">
<h1>The plant generator lt;/h1>
<p>click anywhere in the box to generate a plant</p>
</section>
<div id="plants">
</div>
<script type="text/javascript" charset="utf-8">
const colors = ['red', 'blue', 'green'];
const plantsContainer = document.getElementById('plants');
plantsContainer.addEventListener('mousedown', function(event) {
generatePlant(event.x, event.y, plantsContainer);
});
/**
* Changes the plant's color on click.
* @param {Plant} plant Target to change the color.
* @param {HTMLDivElement} plantElement The plant element.
* @returns undefined
*/
function changeColorOnClick(plant, plantElement) {
let index = plant.getState().colorIndex + 1;
index >= colors.length ? index = 0 : null;
plant.setState({ ...plant.getState(), color: colors[index], colorIndex: index });
plantElement.style.backgroundColor = plant.getState().color;
}
/**
* Generate a plant.
* @param {Number} x The plant's x cordinate.
* @param {Number} y The plant's y cordinate.
* @param {any} appendAt? The element to append the plant at.
* @returns {Plant}
*/
function generatePlant(x, y, appendAt) {
let plant = new Plant();
x = x ?? Math.floor(Math.random() * window.innerWidth);
y = y ?? Math.floor(Math.random() * window.innerHeight);
generatePlantElement(plant, x, y);
console.log(x, y);
return plant;
}
/**
* Generate a plant element.
* @param {Plant} plant The plant.
* @param {Number} x The plant's x cordinate.
* @param {Number} y The plant's y cordinate.
* @param {any} appendAt? The element to append the plant element at [optional].
*/
function generatePlantElement(plant, x, y, appendAt) {
let plantElement = document.createElement("div");
let plantState = plant.getState();
plantElement.classList.add("plant");
plantElement.style.left = `${x}px`;
plantElement.style.top = `${y}px`;
plantElement.style.backgroundColor = plantState.color;
(appendAt || document.body).appendChild(plantElement);
plantElement.onclick = () => changeColorOnClick(plant, plantElement);
}
</script>
</body>
</html>
How to add the position of onClick event to the hook?
In react-leaflet v3
at least the following options could be considered to attach click
event handler on map (also covered in official documentation):
Option 1: via useMapEvents
hook
function MyMap() {
const [loc, setLoc] = useState(null);
const map = useMapEvents({
click: (e) => {
setLoc(e.latlng);
console.log(e.latlng.lat, e.latlng.lng);
},
})
return null
}
export default function App() {
return (
<MapContainer
center={[49.1951, 16.6068]}
zoom={defaultZoom}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
></TileLayer>
<MyMap />
</MapContainer>
);
}
Option 2: via useMapEvent
hook
The difference with option 1, the later one supports attaching a single
event handler to the map instance
function MyMap() {
const [loc, setLoc] = useState(null);
const map = useMapEvent('click', (e) => {
setLoc(e.latlng);
console.log(e.latlng.lat, e.latlng.lng);
})
return null
}
export default function App() {
return (
<MapContainer
center={[49.1951, 16.6068]}
zoom={defaultZoom}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
></TileLayer>
<MyMap />
</MapContainer>
);
}
Option 3: via MapConsumer
component:
function Map() {
const [loc, setLoc] = useState(null);
return (
<MapContainer
center={[49.1951, 16.6068]}
zoom={defaultZoom}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
></TileLayer>
<MapConsumer>
{(map) => {
map.on("click", (e) => {
setLoc(e.latlng);
console.log(e.latlng.lat, e.latlng.lng);
});
return null;
}}
</MapConsumer>
</MapContainer>
);
}
Option 4: using useMap
hook
function MyMap() {
const [loc, setLoc] = useState(null);
const map = useMap();
map.on("click", (e) => {
setLoc(e.latlng);
console.log(e.latlng.lat, e.latlng.lng);
});
return null
}
function App() {
return (
<MapContainer
center={[49.1951, 16.6068]}
zoom={defaultZoom}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
></TileLayer>
<MyMap />
</MapContainer>
);
}
Option 5: event gets attached to underlying map instance once map is created (whenCreated
):
function Map() {
const [loc, setLoc] = useState(null);
function hanleMapCreated(map){
map.on("click", (e) => {
setLoc(e.latlng);
console.log(e.latlng.lat, e.latlng.lng);
});
}
return (
<MapContainer
center={[49.1951, 16.6068]}
zoom={defaultZoom}
scrollWheelZoom={false}
whenCreated={hanleMapCreated}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
></TileLayer>
</MapContainer>
);
}
android imageview onclick behaviour
The best way is to add an OnTouchListener
to the view and handle click event by yourself related to the touch coordinate.
But if you need an easy way which I don't suggest because it can lead to performance issue you can add transparent views on top of your ImageView
and add different OnClickListener
for them.
Get X/Y Coordinates on Button using 'onclick' and JavaScript
You need to pass on the event. This is done as so:
<input type="button" onclick="buttonClick(event)" value="Submit"/>
^
'---- that one there
Related Topics
Trying to Uninstall_Shortcut But Shortcut Won't Go Away
Why Shouldn't I Use System.Out.Println() in Android
How to Tell If the Screen Is on in Android
Android/Firebase - Error While Parsing Timestamp in Gcm Event - Null Timestamp
Picasso Illegalargumentexception Target Must Not Be Null
Android Screen Size Hdpi, Ldpi, Mdpi
No Network Security Config Specified, Using Platform Default - Android Log
Viewpager + Recyclerview Issue in Android
When a Fragment Is Replaced and Put in the Back Stack (Or Removed) Does It Stay in Memory
How to Open the Options Menu Programmatically
How to Use a Timertask to Run a Thread
Retrofit2.0 Gets Malformedjsonexception While the JSON Seems Correct
Android Youtubeplayer with Unauthorized Overlay on Top of Player
How to Use Startactivityforresult() for Email Intent
Android: How to Programmatically Set the Size of a Layout
Android Beginner Difference Between Padding and Margin
How to Get Documents in an Android Directory That Phonegap Will See