Sodasi Web
Sodasi Web

Reputation: 11

How to resize and align to center TextView to ImageView in relative layout - android sdk 10

I'm playing with Android SDK 10 (I want to support devices from sdk 10)

I can't figure how to auto center the text in a Imageview.

The only way I can think of to center the text is to use padding, but I don't like it, it must be a better solution.

  1. Resizing Image from asset is not working

    InputStream ims = context.getAssets().open("myimage.png");
    Drawable d = Drawable.createFromStream(ims, null);
    d.setBounds(0, 0, (int)(d.getIntrinsicWidth()*0.5),
    (int)(d.getIntrinsicHeight()*0.5));
    
    ScaleDrawable sd = new ScaleDrawable(d,0,px,py);
    ims.close();
    Image = new ImageView(context);
    Image.setImageDrawable(sd);
    Image.setAdjustViewBounds(true);
    layout.addView(Image);
    
    TextView t = new TextView(this.context);
    t.setText(r.toString());
    t.setTextSize(80);
    t.setGravity(Gravity.CENTER);
    layout.addView(t);
    

Is there a way to add the text to image asset (ImageView) ?

Right now I added the TextView and ImageView in a RelativeLayout.

What is the best practice to create a group of asset image and text so that when I move the image the text is following (centered )

Upvotes: 0

Views: 697

Answers (3)

Dhananjay Sarsonia
Dhananjay Sarsonia

Reputation: 144

Try this. Keep Framelayout as the parent layout where you are adding the views. Now use LayoutParams to set the ImageView's gravity, height and width.

  LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
  layoutParams.gravity = Gravity.CENTER;
  imageView.setLayoutParams(layoutParams);

Now in the FrameLayout first add the Imageview and then the textview. Do not change anything for the textview.

 frameLayout.addView(imageView);
 frameLayout.addView(text);

Upvotes: 1

Juan Martinez
Juan Martinez

Reputation: 770

You can always add the CENTER_HORIZONTAL rule to the RelativeLayout, so all of its children remain centered horizontally.

Upvotes: 1

Related Questions