in the project, I tried adding a View object dynamically in a RelativeLayout
ImageView card = new ImageView(this);
card.setImageResource(R.drawable.card);
RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(225, 315);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.rightMargin = 40;
parent.addView(card, layoutParams);
after a while, when I tried to get the location of this View, no method works.
As I found in Studio's debug view, the View's layoutparams and all its attrs like mLeft... got the value 0.
So how could I solve the problem? thanks a lot.
It might be because you tried to get position before onLayout has happened.
You might try something like this:
ViewTreeObserver vto=view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override public void onGlobalLayout(){
int [] location = new int[2];
view.getLocationOnScreen(location);
x = location[0];
y = location[1];
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
Also check how to get view's position in coordinates?
You can use these code to get the location:
int loc[]=new int[2];
card.getLocationOnScreen(loc);
int x=loc[0];
int y=loc[1];
If you want to get the location, you have to wait for the View to complete the measurement.
Simple and best way to find a location of view on screen.
view.post(() -> {
xPosition = view.getX());
yPosition = view.getY();
};
view.post() is used because of that if you try to get view location onCreate() method without using post then you get (0,0) because of that view takes few millisecond to inflate on the screen.
Using the Data Binding Library in Android to get location of a view.
private fun getViewLocation(){
val loginBinding = ActivityLoginBinding.inflate(layoutInflater)
val locationX = loginBinding.forgotPasswordBtn.x
val locationY = loginBinding.forgotPasswordBtn.y
// locationX and locationY are returned as Float values
}
Related
I am using Popup Window to derive the tool tip but facing some issue to dynamically place the arrow head according to the position of the anchor view on screen.
One thing what you can do is find the location of the anchored view on the screen and set the x,y coordinate of your pop up layout accordingly. To find the real world coordinates, you can use the following code:
public static Rect locateView(View v) {
int[] loc_int = new int[2];
v.getLocationOnScreen(loc_int);
Rect location = new Rect();
location.left = loc_int[0];
location.top = loc_int[1];
location.right = location.left + v.getWidth();
location.bottom = location.top + v.getHeight() + v.getPaddingTop() + v.getBottom();
return location;
}
Pass your anchored view to the function, and later on, you setX,SetY property of your popup.
Something like:
popUpLayout.setX(locateView(findViewById(R.id.anchor_view)).left);
Second solution, may be you can just put wrap your anchored view and pop up in a linear/relative layout and play with visibility.
I have an ImageViewArray and I am randomizing their locations, I want to check if the current location already contains an ImageView without keeping a lot of values of x,y for every ImageView in the array.
Here is my code:
ImageView[] imageViewArray = new ImageView[40];
for (int i = 0; i < 40; i++) {
imageViewArray[i] = new ImageView(this);
imageViewArray[i].setTag(i);
imageViewArray[i].setImageResource(R.mipmap.enemy);
rlt.addView(imageViewArray[i]);
imageViewArray[i].setX(rand.nextInt(rlt.getWidth()));
imageViewArray[i].setY(rand.nextInt(rlt.getHeight()));
if(imageViewArray[i].getX()=) // here I want to check if it already contains an ImageView.
}
Possible Solution
Creating IntArray and adding X value to it and also every Y value for it, then compare between them, is it the best solution?
Problem with the solution - nothing happens, the imageview doesn't change the place and the Toast is not executed.
code:
ImageView[] imageViewArray = new ImageView[20];
ArrayList<Float> xarray = new ArrayList<>();
ArrayList<Float> yarray = new ArrayList<>();
for (int i = 0; i < 20; i++) {
imageViewArray[i] = new ImageView(this);
imageViewArray[i].setTag(i);
imageViewArray[i].setImageResource(R.mipmap.enemy);
imageViewArray[i].setX((float)rand.nextInt(1 + layoutwidth));
imageViewArray[i].setY((float)rand.nextInt(1 + layoutheight));
xarray.add(imageViewArray[i].getX());
yarray.add(imageViewArray[i].getY());
rlt.addView(imageViewArray[i]);
Toast.makeText(MainActivity.this,imageViewArray[i].getX() +"blabla",Toast.LENGTH_LONG);
}
EDIT
layoutwidth is zero :
private int layoutwidth, layoutheight, randx, randy;
private RelativeLayout rlt;
....
rlt = (RelativeLayout) findViewById(R.id.layout);
rlt.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
rlt.getViewTreeObserver().removeOnGlobalLayoutListener(this);
layoutwidth = rlt.getWidth();
layoutheight = rlt.getHeight();
}
});
Yes, that is the best solution. You need to load the rectangles from somewhere. You might merge rectangles if one contains the other, but then you would over-complicate your task and in your quest of writing a more performant and a clearer code, you would end up with a slow and complicated code. Write your code with storing pairs of X, Y points where X is the let-top corner position and Y is the right-bottom corner position.
Note, that I have assumed that the pictures are not rotated. If the images might be rotated, then you need a more general solution, using the inequalities defining the rectangles to see where a point set of a rectangle intersects the point set of the other rectangle. If the intersection is empty set, then the "space is not used up".
I have an Android related issue:
I am trying to centre a logo on the screen of my device, but it won't position correctly.
I am using the following function:
public void ImageCentered(int ID){
ImageView iv = (ImageView) findViewById(ID);
int x = 0;
int y = 0;
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
x = (screenWidth/2)-(iv.getWidth()/2);
y = (screenHeight/2)-(iv.getHeight()/2);
position.setMargins(x, y, 0, 0);
iv.setLayoutParams(position);
}
This could should work,but it won't. The image is set off slightly to the right and bottom like in this image:
https://www.dropbox.com/s/tf7r1u1xqcmb9t9/2014-08-16%2018.36.04.png
Now, the strange thing is, when I use the following code:
public void ImageCentered(int ID){
ImageView iv = (ImageView) findViewById(ID);
int x = 0;
int y = 0;
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
x = (screenWidth/2)-(iv.getWidth()/2);
y = (screenHeight/2)-(iv.getHeight()/2);
position.setMargins(x, y, 0, 0);
Message(IntToStr(x)+", "+IntToStr(y));
iv.setLayoutParams(position);
}
this is the result:
https://www.dropbox.com/s/mjw80zlzkav6dzs/2014-08-16%2018.41.16.png
Side note: The text in the Message() function does not matter, nor does its position within the ImageCentered() function.
I am not calling the function in my OnCreate(), as the width and height of the image would always return 0, so I looked something up and found this:
#Override
public void onWindowFocusChanged(boolean hasFocus){
ImageCentered(R.id.image);
}
This piece of code is in my MainActivity.java file, whereas the ImageCentered() function is in my UtilLib.java file.
So, I was wondering: What's going on here? Why does the code work when I pop in a Message() but not when I leave it out?
Sure, I can try hardcoding the data, but what about smaller/bigger screens?
I hope an Android guru can help me out here, as I've been struggling with this for quite some time now.
EDIT
Just noticed something interesting when pressing "OK" on my Message:
https://www.dropbox.com/s/a7lu6588hy1opw7/2014-08-16%2018.51.55.png
My guess is that my problem lies there, but after clicking the "OK" button once more, the data is "492, 207" again. scratches head
Assuming rom your code that the ImageView is inside a RelativeLayout, You could also do:
// get imageview layout params or create new ones
RelativeLayout.LayoutParams params = imageView.getLayoutParams();
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
this way the image will be automatically centered without all those manual calculations!.
You can also specify it in the XML with
<ImageView .....
android:layout_centerHorizontal="true"/>
I've ultimately decided to just hardcode the x and y coordinates, and later on use some sort of scaling-conversion to position them properly, unless someone can provide me with a better method of fixing this.
UPDATE
So, after googling after a while (again), I have finally found the answer and created two functions:
public int GetImageHeight(int ID){
ImageView iv = (ImageView)findViewById(ID);
iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());
return iv.getMeasuredHeight();
}
public int GetImageWidth(int ID){
ImageView iv = (ImageView)findViewById(ID);
iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());
return iv.getMeasuredWidth();
}
All you have to do is pass the ID of the image you made in your xml file, like so:
GetImageHeight(R.id.logo)
I'm wondering what would be the best solution to get to the result shown below.
Here is what i've found so far:
an ImageView for the forest and a transparent surfaceView (to handle touch) on which I would draw the rectangles?
Or...
Just One SurfaceView with the image set as background and rectangles directly drawn on...?
For those 2 I've already chosen a RelativeLayout.
Which of those 2 would be the most efficient and easiest to do?
Or maybe there is another way which I haven't think about.
In any case thanks for your advice, here is what I tend to...
I've implemented this by placing the image in a RelativeLayout (FrameLayout would work too), and then adding each outlined view programatically. If you know the x and y origin (perhaps as a ratio to the image) and the size for each area, you can easily inflate each view/area (with a black border, transparent center), make it clickable and set a listener, and then set it's origin by adjusting it's margins. You may want to perform all of this after the image has finished laying out:
I put this in onActivityCreated of my Fragment, but other lifecycle methods would work too...
ViewTreeObserver vto = image.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (image.getMeasuredHeight() > 0) {
addHotSpots();
ViewTreeObserver obs = image.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}
}
});
And this is how I actually place all the hotspots/areas:
protected void addHotSpots() {
HotSpot[] hotSpots = res.hotspots;
for (HotSpot hs : hotSpots) {
addHotSpotToImage(hs);
}
private void addHotSpotToImage(HotSpot hs) {
int height = image.getMeasuredHeight();
int width = image.getMeasuredWidth();
//this piece will probably be different for you
//depending on what you know about the area's intended size/position
double hsHeightRatio = hs.lr.y - hs.ul.y;
double hsWidthRatio = hs.lr.x - hs.ul.x;
double leftMargin = hs.ul.x * width;
double topMargin = hs.ul.y * height;
double hsHeight = height * hsHeightRatio;
double hsWidth = width * hsWidthRatio;
LayoutInflater vi = (LayoutInflater) image.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newSpot = vi.inflate(R.layout.question_hotspot, null);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) hsWidth, (int) hsHeight);
newSpot.setTag(hs.key);
newSpot.setFocusable(true);
newSpot.setClickable(true);
newSpot.setFocusableInTouchMode(true);
newSpot.setOnTouchListener(this);
params.topMargin = (int) topMargin;
params.leftMargin = (int) leftMargin;
image.addView(newSpot, params);
}
I'm trying to make a dynamic grid layout, it being API 10+ is the part that's been making it slow going. I tried to make it wrap automatically.. but in the end found it easier just to try to force it into a grid pattern using coordinates. This script was working by itself when I did the positioning at time of creation, but now I am trying to loop through each item as a sort. So if one item is deleted, they all float back into a grid without a hole in the middle.
Problem is, it seems the layout parameters are only applying to the last object.
Here's some base variables and onCreate setup:
int screenWidth;
int screenHeight;
int distStep = 130;
int leftPad = 20;
int numCols;
int baseID = 0;
android.util.DisplayMetrics metrics = this.getResources().getDisplayMetrics();
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
numCols = (int) (screenWidth - leftPad) / distStep;
int scrRemain = screenWidth - ((numCols * distStep) + leftPad);
distStep += (int) scrRemain / numCols;
Then on to the main function for adding:
public void addObjToLayout() {
RelativeLayout relLay = (RelativeLayout) this.findViewById(R.id.mainWindow);
for(int i = 1; i <= currQuantity; i++){
TextView tv=new TextView(this);
tv.setTextSize(40);
tv.setId(baseID + i);
tv.setPadding(24, 4, 24, 4);
tv.setBackgroundColor(0x110000FF);
tv.setText(String.valueOf(baseID + i)); //Val for debugging
tv.setTextColor(0xFFFFFFFF);
relLay.addView(tv);
}
baseID += currQuantity;
sortLayout();
}
Then the sorting:
public void sortLayout() {
int leftNum = 20;
int topNum = 0;
for(int i = 1; i <= baseID; i++){
TextView tv= (TextView) this.findViewById(baseID);
MarginLayoutParams mp = new MarginLayoutParams(tv.getLayoutParams());
mp.setMargins(leftNum, topNum, 0, 0);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mp);
tv.setLayoutParams(lp);
leftNum += distStep;
if(leftNum >= distStep * numCols){
leftNum = leftPad;
topNum += distStep;
}
}
}
What I am getting is all the textViews pile up in the top left corner, except the last one which is positioned exactly where it should be. So it seems in my head, the params object isn't applying until the loop ends or something.. but logically I don't see why.
As I said, this worked when I set the params at the get go, problem is mass updating them all at once. I am pretty new to android, so I hope I'm not just doing something stupid.
Thanks for your time
Margin means it will set a gap between the previous view and current view.
When you add view1, view2 and view3 to grid layout and if you remove view2 at some point of time, then the margin for view3 is set according to view1. So, it won't leave empty space in place of view2. Instead of removing view2 at run time, set the background for view2 as null and set the text as empty as below.
textView.setBackground(null);
textView.setText("");
So that the view is still available but looks as deleted.
Started looking into GridView using an extended baseAdapter. Looks promising:
For more (see #2):
http://www.mkyong.com/android/android-gridview-example/