simplify
simplify

Reputation: 109

Place a textView in the middle of imageView programatically android

I have an ImageView and a TextView declared programatically(not in any xml).

ImageView img = new ImageView(this);
TextView txt = new TextView(this);
        LinearLayout.LayoutParams coordinates = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

img.setLayoutParams(coordinates);
img.setImageResource(R.drawable.img);
txt.setText("a");

How could I place the text in the middle of the imageview ? I need that "a" to be always in the middle of imageView.

Upvotes: 0

Views: 600

Answers (3)

user8259253
user8259253

Reputation:

To centralize the text programmatically, you just need to use gravity

ImageView img = new ImageView(this);
TextView txt = new TextView(this);
LinearLayout.LayoutParams coordinates = new 
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
LinearLayout.LayoutParams.WRAP_CONTENT);

img.setLayoutParams(coordinates);
img.setImageResource(R.drawable.img);
txt.setText("a");
txt.setGravity(Gravity.CENTER);

To show it in the middle of ImageView, you can further extend ImageView width to MATCH_PARENT so that the text will always appear in the middle of Imageview

Upvotes: 1

user8626261
user8626261

Reputation:

Using Pragmatically you can set it

   RelativeLayout relativeLayout=new RelativeLayout(context);
//set Relative Layout Parameter using 
RelativeLayout.LayoutParams relativeLayoutParams=new RelativeLayout.LayoutParams(RelativeLayout.MATCH_PARENT,RelativeLayout.MATCH_PARENT);
relativeLayout.setLayoutParams(relativeLayoutParams);

First create ImageView

ImageView imageView=new ImageView(context);
relativeLayout.addView(imageView);

Then set text view on it

TextView textView=new TextView(context);
relativeLayout.addView(textView);

Upvotes: 1

kodlan
kodlan

Reputation: 631

Maybe you should just have an text view and use image as a background:

textView.setBackgroundResource(R.drawable.img);

Upvotes: 1

Related Questions