songoku1610
songoku1610

Reputation: 1744

Can't place ImageView at top corner at runtime

I want to place a ImageView at top left corner when runtime, but it does not work. This is my layout and code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
    android:id="@+id/layout_main"
    android:layout_height="fill_parent" tools:context=".Main">
</RelativeLayout>

This is code:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout_main);
ImageView imageView =new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.green_apple);
imageView.setScaleX(0.3f);
imageView.setScaleY(0.3f);
imageView.setLeft(0);
imageView.setTop(0);
layout.addView(imageView);

I also tried:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout_main);
ImageView imageView =new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.green_apple);
imageView.setScaleX(0.3f);
imageView.setScaleY(0.3f);
imageView.setX(0);
imageView.setY(0);
layout.addView(imageView);

And:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout_main);
ImageView imageView =new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.green_apple);
imageView.setScaleX(0.3f);
imageView.setScaleY(0.3f);
layout.addView(imageView);
set = new AnimatorSet();        
ObjectAnimator aniX = ObjectAnimator.ofFloat(imageView, "x", 0);
aniX.setDuration(100);
ObjectAnimator aniY = ObjectAnimator.ofFloat(imageView, "y", 0);
aniY.setDuration(100);
set.playTogether(aniX, aniY);
set.start()

But same result, this is my result:enter image description here

Always have large space to Top and Left screen, Although I set 0,0. I also try set height and width of screen, it fly out of screen. I don't know why. Thank you very much for anyone can explain and how to help me fix it

Upvotes: 0

Views: 73

Answers (1)

rainash
rainash

Reputation: 874

That is because you use setScaleX and setScaleY, so try the code below:

    final ImageView iv = new ImageView(context);
    iv.setImageResource(R.drawable.green_apple);
    rl.addView(iv);
    iv.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {

        @Override
        public boolean onPreDraw() {
            iv.getViewTreeObserver().removeOnPreDrawListener(this);
            int w = (int) (iv.getWidth() * 0.3);
            int h = (int) (iv.getHeight() * 0.3);
            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(w, h);
            iv.setLayoutParams(rlp);
            return true;
        }
    });

Upvotes: 1

Related Questions