Get coordinates of a programatically created imageview Android - android

So i am creating my views programatically like so:
for (int i = 0; i < num_devices; i++) {
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = new LinearLayout.
LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
try {
Class res = R.drawable.class;
Field field = res.getField(device_types.get(i));
int resId = field.getInt(null);
imageView.setImageResource(resId);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
LinearLayout link_devices = (LinearLayout) findViewById(R.id.link_devices);
link_devices.addView(imageView);
}
And i am trying to get the coordinates of the imageview:
I have tried the following methods, but am getting no where
imageView.getDrawable().getBounds().centerX() /centreY
imageView.getX() / getY
imageView.getLocationInWindow(); / onScreen();
Could someone please explain to me how to get the cooridinates of the image which is a drawable so i can draw a box around it or draw lines between two images (that is the planned functionality)

int top = imageView.getTop();
int left = imageView.getLeft();
From there you have the top-left point coordinates.

Related

Regenarate location if (X,Y) already contains ImageView there

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 want to redraw on a view Android programming

I am creating an app that displays the graphs of input given by a user. The graph is drawn on a linear layout using some library..i want the linear layout to redraw the new function requested by the user everytime the user clicks the draw button..I have tried using layout.invalidate() but this is not working in my app.please help ..below is code snipet :
bb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String text = ee.getText().toString(); // getting the user expression input
LinearLayout layout = (LinearLayout) findViewById(R.id.graph2);
layout.setVisibility(View.INVISIBLE);
Expression data = Expression.createExpression(text) ;
if(text == ""){
Toast.makeText(getApplicationContext(), "please enter a valid equation", Toast.LENGTH_LONG).show();
layout.setVisibility(View.INVISIBLE);
}
else
{
draw(data) ;
layout.setVisibility(View.VISIBLE);
layout.invalidate();
}
}
});
public void draw(Expression x)
{
final GraphView graphing = new LineGraphView(this, "sketch");
int num = 350;
GraphViewData[] array = new GraphViewData[num];
double w=0;
for (int i=0; i<num; i++) {
w += 0.2;
array[i] = new GraphViewData(i, x.evaluate(w,0,0)); }
// add data
graphing.addSeries(new GraphViewSeries(array));
// set view port, start=2, size=40
graphing.setViewPort(0, 120);
graphing.getGraphViewStyle().setNumHorizontalLabels(2);
graphing.setScrollable(true);
// optional - activate scaling / zooming
graphing.setScalable(true);
LinearLayout layout = (LinearLayout) findViewById(R.id.graph2);
layout.addView(graphing);
layout.invalidate();
}
First:
graphing.setViewPort(0, 120);
is it correct? To me it looks like you set view width to 0.
Next, you sure you don't want to discard old results by removing old views from layout?
Last, layout auto-invalidated when you add or remove child views.

Getting view inside dialog from outside the dialog

i try to lazy load image to images inside dialog.
My problem is that i cant get the views from my dialog outside of the dialog to update the images.
I try to give each view unique id and then find the view by its id but i get null pointer exception.
Here is my dialog code:
public void showAllComents() {
builderComment = new AlertDialog.Builder(this);
builderComment.setTitle(dietsList[poisition][0] + " comments");
View prefView = View.inflate(this, R.layout.show_comments, null);
builderComment.setCancelable(false);
editComment = (EditText) prefView.findViewById(R.id.editComment);
LinearLayout commentsLinear = (LinearLayout) prefView.findViewById(R.id.commentsLinear);
if (haveComments) {
int length = comments.length;
for (int i = 0; i < length; i++)
{
LinearLayout tempLinear = new LinearLayout(this);
LayoutParams p1 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
if (i != 0)
p1.setMargins(0, 20, 0, 0);
tempLinear.setOrientation(LinearLayout.HORIZONTAL);
tempLinear.setLayoutParams(p1);
ImageView image = new ImageView(this);
p1 = new LayoutParams(64, 64);
image.setLayoutParams(p1);
image.setId(6000+i);
image.setImageDrawable(getResources().getDrawable(R.drawable.anonymous));
tempLinear.addView(image);
commentsLinear.addView(tempLinear);
}
...
...
... \\\Rest of dialog code...
I load my images and then i try to update the imageviews.
public void setCommentedUsersProfilePictrue()
{
int lengthUnique = commentsuniqueNames.length;
int loadLength = comments.length;
View prefView = View.inflate(this, R.layout.show_comments, null);
for(int i = 0; i < loadLength; i++)
{
for(int j = 0; j < lengthUnique; j++)
{
if(comments[i][1].equals(commentsuniqueNames[j]))
{
Log.i("user name comment", comments[i][1]);
//Log.i("user name", userProfilePictures[i][1]);
ImageView tempImage = new ImageView(DietWall.this);
tempImage = (ImageView) prefView.findViewById(6000 + i);
if(tempImage != null && commentsLoadedPictrues[j][1] != null && commentsLoadedPictrues[j][1].equals("null") == false && commentsLoadedPictrues[j][1].equals("NULL") == false)
tempImage.setImageDrawable(new BitmapDrawable(getResources(),decodeBase64(commentsLoadedPictrues[j][1])));
else
Log.i("null", "null");
}
}
}
}
you need the view of your dialog, you should find your imageView like so:
View ImageView image = dialog.findViewById(R.id.image);
but i suggest using the following library, it takes care of image loading/caching and much much more, it just makes your life easier ;-)
https://code.google.com/p/android-query/#Image_Loading
//fetch and set the image from internet, cache with file and memory
aq.id(R.id.image1).image("http://www.vikispot.com/z/images/vikispot/android-w.png");
Features:
Simple
Memory & File Caching
Down Sampling
Zoomable (WebView)
Fallback Image
Preloading
Animation
Dynamic Aspect Ratio
Avoid Duplicated Simultaneous Fetches
Custom Callback

how to programmatically add an image to a activity android

Hi I am trying to programatically add an image to an activity for an android app
I have this :
for (int i = 0; i < num_devices; i++) {
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams
(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);
try {
Class res = R.drawable.class;
Field field = res.getField(device_types.get(i));
int resId = field.getInt(null);
imageView = (ImageView) findViewById(resId);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
LinearLayout link_devices = (LinearLayout) findViewById(R.id.link_devices);
link_devices.addView(imageView);
however it doesnt let me get the location of the images ( i try and get 0 for getTop, getLeft etc..)
am i doing it wrong and was is the correct way to do it
You are not setting image on that imageview, and you have set WRAP_CONTENT as layout params, which means the size of the imageView is same as size of image you are setting on it.
Since no image is attached the imageView size is 0.
Try setting an image, using any one of the codes ;- imageView.setImageBitmap(Bitmap bm), setImageDrawable(Drawable drawable) or setImageResource(int ResID).
I don't get what you're doing the with this code & its not required:
Class res = R.drawable.class;
Field field = res.getField(device_types.get(i));
int resId = field.getInt(null);
imageView = (ImageView) findViewById(resId);

android- Placing two programatically created imageView next to each other in a RelativeLayout

I have created two imageViews promatically as shown below:
public void createImageViews(Integer count){
ImageView[] imageViewArray = new ImageView[count];
for (int i = 0; i < count; i++ ) {
imageViewArray[i] = new ImageView(getBaseContext());
imageViewArray[i].setId(i); // unique property for every imageView
if(i==0){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
imageViewArray[i].setLayoutParams(params);
imageViewArray[i].setBackgroundResource(imagesForIv[i]);
_UIRLParent.addView(imageViewArray[i]);
Log.v("first", "first"+i);
}
else if(i < 3){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF,imageViewArray[i].getId());
imageViewArray[i].setBackgroundResource(imagesForIv[i]);
_UIRLParent.addView(imageViewArray[i],params);
Log.v("second", "second"+i);
}
}
I just need to place the second imageView toRightOf first imageView. Can someone help me. This is eating away a lot of my time.
try https://stackoverflow.com/a/5191159/1436931
you are using wrong index values.
at line
params.addRule(RelativeLayout.RIGHT_OF,imageViewArray[i].getId());
you aligning current image RIGHT of current image. :)
you need to track the index of last imageView id i.e left Image view
you need something like this
params.addRule(RelativeLayout.RIGHT_OF,imageViewArray[i-1].getId());

Categories

Resources