Align image and text on textview

♀尐吖头ヾ 提交于 2020-01-03 04:18:35

问题


In my app, I populate a linearlayout with a text and a little icon (like a listview with a custom adapter). I need the text and the picture to have the same size. Is there a way to do that?

Here's the code:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
              LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
      LinearLayout LayoutPadre = new LinearLayout(this);
TextView Tag = new TextView(this);
      ImageView img = new ImageView(this);

      Tag.setText(data);
     if(stato.equalsIgnoreCase("presente")){
      img.setImageResource(R.drawable.ic_presente); 
     }else{
         img.setImageResource(R.drawable.ic_assente);  
     }

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(75, LayoutParams.WRAP_CONTENT);   //Here I need the img to have same size as the text, but Tag.getHeight() returns 0
      layoutParams.setMargins(50, 0, 0, 0);

      img.setLayoutParams(layoutParams);

      LayoutPadre.setLayoutParams(params);

      LayoutPadre.addView(Tag);
      LayoutPadre.addView(img);

The problem is that the image is not horizontally centered like the img. Look at the screen

Thanks to all.


回答1:


keep the layout_height of text and image as Match_Parent and not Wrap_Content... By that




回答2:


If you are preserving the android:layout_height="wrap_content" or it did not work, you can also do android:gravity="center"



来源:https://stackoverflow.com/questions/24390096/align-image-and-text-on-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!