Reputation: 637
I have a ImageView that I need get Image Width and Height in Java and store them in some variables and use it some times that I need, but when I want save height and width values it will return NULL value to message string.
I created some outside method and pass value to it for store values but it didn't work too, Also i created a Text View and I assigned values to TextView text, it showed in screen but when I used getText()
for get text it got default text of Text view, look, there is no any way for get value from inner class, is there any way get value from anonymous inner class?
final String[] message = new String[2];
final ImageView iv = (ImageView)findViewById(R.id.main_item2);
final TextView tv = (TextView)findViewById(R.id.storePostions);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
iv.getViewTreeObserver().removeOnPreDrawListener(this);
int finalHeight, finalWidth;
finalHeight = iv.getMeasuredHeight();
finalWidth = iv.getMeasuredWidth();
message[0] = String.valueOf(finalHeight);
message[1] = String.valueOf(finalWidth);
return true;
}
});
Toast.makeText(MainActivity.this, "finalHeight = " + message[0] + " ,finalWidth = " + message[1], Toast.LENGTH_LONG).show();
// show "finalHeight = NULL ,finalWidth = NULL"
Upvotes: 0
Views: 468
Reputation: 5087
Your code should get the values just fine, your problem is that you're outputting it before that code runs. All of the code in onPreDraw()
is not executed immediately, but rather defined and set to be run later, whenever vto
's "preDraw" event happens. Your call to Toast.makeText
then happens before that "later" comes.
To delay the Toast.makeText()
call, you have two options. You can put it in a similar "run this later" block, or you can use an inter-thread coordination tool of some sort. For the former option, add another OnPreDrawListener
and put the call in there. You already know how to do that.
For the latter option, I recommend a CountDownLatch
. Initialize it up top with a count of 1, countDown()
on it at the end of onPreDraw()
, and await()
on it before calling Toast.makeText()
. This will guarantee that, by the time the await()
call returns, the code with the countDown()
call has finished. Note that this only works if the two code sections run in different threads. Otherwise, it will just stall forever. I'm pretty sure they do run in different threads in this case, but keep that in mind in general.
Upvotes: 1