Android add buttons on image programmatically - java

I have an image inside of a Constraint layout, I want to programmatically add buttons to it, so it makes sense with the image. Imagine an image of multiple squares where each square should correspond with a button.
I let it scale the image so it takes up the entire width of the screen.
I know the pixel coordinates of where the button should be located but I'm having trouble placing them correctly on the screen.
I tried converting the pixel location to the location on the screen by getting the width of the screen to calculate the multiplier which should be the same horizontally and vertically as it keeps the aspect ratio. But it's off by quite a bit.
float mult = ((float) x) / ((float) SIZE_IMG.x); # x is the width of the screen
ConstraintLayout viewById = context.findViewById(R.id.constraintLayout);
ConstraintSet constraintSet = new ConstraintSet();
Button button = new Button(context);
button.setId(View.generateViewId());
viewById.addView(button);
constraintSet.clone(viewById);
constraintSet.connect(button.getId(), ConstraintSet.START, R.id.constraintLayout, ConstraintSet.START, (int) (mult * START.x));
constraintSet.connect(button.getId(), ConstraintSet.TOP, R.id.constraintLayout, ConstraintSet.TOP, (int) (mult * START.y));
constraintSet.applyTo(viewById);
X is found by
ViewTreeObserver vto = viewById.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
viewById.getViewTreeObserver().removeOnPreDrawListener(this);
int finalHeight, finalWidth;
finalHeight = viewById.getHeight();
finalWidth = viewById.getWidth();
yellowScoreBoard.initBoardOn(finalWidth, finalHeight, mainActivity);
return true;
}
});

Related

How to get the middle of the screen for API>=19

The button should move to the middle of the screen when clicked. But every time I get different position of button in different devices. And I don't know how can I fix it.
This code what I use:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
float middleScreen = metrics.xdpi;
final TranslateAnimation animation = new TranslateAnimation(0, -middleScreen, 0, 0);
animation.setDuration(3000);
animation.setFillAfter(true);
buttonToNextView.setAnimation(animation);
First of all, what DisplayMetrics.xdpi gave us is the exact physical pixels per inch of the screen in the X dimension which is not the number of pixels on the x-axis.
So, we should use half of widthPixels and heightPixels (based on screen orientation) to achieve the middle of the screen on the x-axis.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
boolean isDisplayPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
float middleScreen = isDisplayPortrait ? metrics.widthPixels / 2 : metrics.heightPixels / 2;
final TranslateAnimation animation = new TranslateAnimation(0, -middleScreen, 0, 0);
animation.setDuration(3000);
animation.setFillAfter(true);
buttonToNextView.setAnimation(animation);
Notice that to place the button exactly at the middle of the screen, you need to subtract half of its width from the middleScreen value.

Android add imageview programmatically fix size all screen

I'm creating several ImageViews programmatically, but I'm running into an issue where there are different ImageView sizes on different displays.
I want the ImageView size to be fixed on all screens. Here is how I am generating those ImageViews:
for (int i = 0; i < myImageList.size(); i++) {
ImageView iv = new ImageView(this);
iv.setImageResource(myImageList.get(i));
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(420, 210);
lp.gravity = Gravity.CENTER;
iv.setLayoutParams(lp);
float angleDeg = i * 360.0f / myImageList.size() - 70.0f;
float angleRad = (float) (angleDeg * Math.PI / 180.0f);
iv.setTranslationX(320 * (float) Math.cos(angleRad));
iv.setTranslationY(320 * (float) Math.sin(angleRad));
iv.setRotation(angleDeg + 80.0f);
main.addView(iv);
final int finalI = i;
}
You could introduce new class derived from ImageView and make all those adjustments in that class. Then just replaces ImageView to your class implementation in layouts etc
There are multiple interpretations of your questions.
The ImageView should have same size on all the devices - use dp. You are using pixels right now in the LayoutParams.
The ImageView should look that it has same size on all screens - find the width and height of the screen, set an aspect ration, eg. 0.33 and use that factored width and height in LayoutParams.
Use MATCH_PARENT in LayoutParams for width as well as height and the ImageView will take the full size (of the parent).
This question has a lot of great explanation about dp, px, sp that could be useful - What is the difference between "px", "dip", "dp" and "sp"?
To find screen sizes
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
// these are sizes in pixels
metrics.widthPixels, metric.heightPixels
Then, you can use this
iv.setScaleType(ImageView.ScaleType.FIT_XY);
See this link for all ScaleType values
Android ImageView ScaleType: A Visual Guide

Resize View in dp

I'm stuck trying to resize the width of a View in a ListView programmatically, because I want it to be in DP, not pixels.
My ListView generate instances of a RelativeLayout with a View that fills all the screen (match_parent), and a TextView and a button inside.
The View is set to width = match_parent to fill the whole screen, as intended
What I want, is to have different View width in my adapter. Like 25%, 50%, or 75% of the total width of the base View.
mRelativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(**[VALUE I NEED HERE]**, mRelativeLayout.getLayoutParams().height));
The ImageView is set to width = match_parent
So this are the relevant parts of code in my ViewList adapter :
RelativeLayout mRelativeLayout = (RelativeLayout) convertView.findViewById(R.id.test_layout);
mRelativeLayout.setBackgroundResource(arrayListName.myColor);
if (arrayListName.myColor == R.color.custom ) {
dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 25% , dayviewLayout.getLayoutParams().height));
}
if (days.mMoodColor == R.color.custom2) {
dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 50% , dayviewLayout.getLayoutParams().height));
}
if (days.mMoodColor == R.color.custom3) {
dayviewLayout.setLayoutParams(new RelativeLayout.LayoutParams( 75% , dayviewLayout.getLayoutParams().height));
}
The 25-50-75% are obviously wrong, as it takes only int values. I want it to fit any screen.
Thanks for your support.
dp units are just px units multiplied by the current screen density, which is available via the DisplayMetrics class:
float density = [some context].getResources().getDisplayMetrics().density;
int dp = (int) ([your px value] * density);

place images inside a layout android

I want to place some images (triggered on click action) inside a layout. I have to place them such that they don't get out of the parent layout.
Code I'm using to add a new image on clicking the layout:
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
ImageView image = new ImageView(this);
LinearLayout.LayoutParams coordinates = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.setLayoutParams(coordinates);
image.setImageResource(R.drawable.image);
layout.addView(image);
If I press on the layout , I must see my imageView put randomly.
Random random = new Random();
int x = random.nextInt(layout.getWidth());
int y = random.nextInt(layout.getHeight());
image.setX(x);
image.setY(y);
But this won't do it. And I see those images outside my layout too.
You are setting x & y which are upper left-top corner - starting point of image to display it. As x/y value can be right/bottom corner, therefore, your image goes out of layout in that case.
Please note - x, y are starting point from where your image will be drawn.
You need to make sure that layoutWidth - x >= imageWidth and layoutHeight - y >= imageHeight.

Relative coordinates of an ImageView in Android

I have a square image in an ImageView contained within a FrameLayout that is right aligned (landscape layout). The FrameLayout is set to FillParent width and height and the ImageView is set to Adjust View Bounds so that the resulting ImageView is a perfect square with each side being the length of the height of the landscape layout, right aligned. However, the original image is larger than this.
I need to get the coordinates clicked on the ImageView in relation to itself (ie. the top left hand corner of the ImageView is 0,0 and the bottom right corner would be the displayed width and height coordinates) so that I can work out if the clicked point was past the mid-point of the ImageView.
I initially get the size of the ImageView using:
int myImageViewWidth = imageView.getWidth();
int myImageViewHeight = imageView.getHeight();
I've created an OnTouchListener and within this I'm using event.getX() and event.getY(), but this seems to return the coordinates relative to the image's oiginal size, not the displayed size. I've also tried the following:
Matrix m = imageView.getImageMatrix();
float[] values = new float[9];
m.getValues(values);
float relativeX = (event.getX() - values[2]) / values[0];
float relativeY = (event.getY() - values[5]) / values[4];
But again this seems to return inaccurate coordinates. Can anyone please help?

Categories