【问题标题】:Centerally aligned text over ImageView in android Linear Layoutandroid Linearlayout中ImageView上的中心对齐文本
【发布时间】:2013-04-20 14:54:04
【问题描述】:

如何在带有线性布局的 android ImageView 上显示文本。为此,我找到了很多关于堆栈溢出的示例,但都是针对相对布局、框架布局但我在线性布局中没有得到它。

我尝试了android:text="My Text",但它不起作用。

如果可能的话,请建议我。如果可以的话怎么办。

 <ImageView
    android:id="@+id/share_button"
    android:layout_width="fill_parent"
    android:layout_height="25dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:layout_weight="2"
    android:text="text"
    android:background="@drawable/iosbutton" />

这是附加到此 ImageView 的图像,我想在其上显示文本。

【问题讨论】:

  • 取一个 TexView 或 Button 设置它的背景如上图和 setText 为他们..
  • @pragnani 我无法更改元素类型,因为它已经由一位开发人员编码并且她不允许更改类型。
  • 尝试说服她“不允许”这样的更改可能不是最好的。
  • @MaciejGórski 我跟她谈过,她很生气,然后就不管了,但我告诉她,如果你能稍微改变点什么,我会做任何你想做的事。谢谢 MaciejGórski。

标签: android android-layout android-imageview


【解决方案1】:

试试这个

使用这个方法

public BitmapDrawable writeOnDrawable(int drawableId, String text){

    Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);

    Paint paint = new Paint(); 
    paint.setStyle(Style.FILL);  
    paint.setColor(Color.BLACK); 
    paint.setTextSize(20); 

    Canvas canvas = new Canvas(bm);
    canvas.drawText(text, 0, bm.getHeight()/2, paint);

    return new BitmapDrawable(bm);
}

这样打电话

ImageView image=(ImageView)findViewById(R.id.imageView1);  
image.setImageDrawable(writeOnDrawable(R.drawable.ic_launcher,"Hello"));

【讨论】:

  • 这是一个有趣的解决方案,虽然不完整:以像素为单位的硬编码字体大小和错误的定位。
  • @MaciejGórski 如果您发现以下问题的 cmets,我已经建议他使用 TextView 或 Button,在您评论某人的答案是否正确之前。而且根据图像大小动态更改字体大小并不是一项艰巨的任务,他会处理的……这有什么好玩的。?
  • @pragnani 是的,这就是我想要的但是还有一件事不能只用 ion xml 来完成。我今天所有的投票都用完了
  • @Nikhil 不可能来自 Xml
  • @Pragnani。好的谢谢。我知道以前也帮助过我一些地方。 Thnak 你可以给我你的邮件 ID。
【解决方案2】:

必须是 ImageView 吗?

<TextView
    android:id="@+id/share_button"
    android:layout_width="fill_parent"
    android:layout_height="25dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:layout_weight="2"
    android:text="text"
    android:gravity="center"
    android:background="@drawable/iosbutton" />

【讨论】:

  • 这个答案是正确的(如果是 id/share_button 则使用 Button)。无论出于什么奇怪的原因,如果您无法更改 share_button 类型,您可以始终将 TextView 添加到布局中并将其与 share_button 对齐。使用 RelativeLayout 时很容易:layout_alignTop、_alignLeft 等都设置为 share_button。
  • @MaciejGórski 但他的要求是使用 ImageView 检查以下问题的 cmets..这并没有提供答案
  • @Pragnani 你说得对。 MaciejGórski 这不是我想要的。
  • @Pragnani 取消删除它让我看看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 2011-06-04
相关资源
最近更新 更多