如何将视图始终置顶?

3
我有一个TextView控件,它在一张图片上。当我点击按钮时,TextView的背景颜色会改变,但是图片不会消失。例如:
初始时我的TextView如下所示: enter image description here 当我点击按钮后: enter image description here
4个回答

1

如果你想仅使用一个 TextView 来完成这个任务,可能是不可能的。因此,我建议你使用 FrameLayout 完成。你可以按照以下方式编写布局。

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FFFFFF" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</FrameLayout>

当您想要更改TextView背景颜色时,请按以下方式更改ImageView背景...
ImageView mageView view = (ImageView) findViewById(R.id.image);
view.setBackgroundColor(Color.BLUE);

但是我想动态地改变图像(星号)和背景颜色。我该怎么做? - Utku Soytaş
谢谢。这对我很有用。 - Utku Soytaş

1
如果必须使用TextView和ImageView,您可以将它们包装在FrameLayout中(此组件应仅包含一个子元素)。FrameLayout会将所有包含的子元素放置在同一“位置”,因此它们会重叠。

或者当需要更多元素时,您还可以使用RelativeLayout并为您的元素提供相同的布局规则(例如,全部居中)。


0
你应该使用 ImageView 而不是 TextView,因为:
public void onClick(View v){
  imageView.setBackgroundColor(Color.GREEN);
}

我必须使用TextView :) - Utku Soytaş
没问题,这是相同的代码,只需要在我的示例中将imageView更改为TextView。 - kodamirmo
但是这并不提供我想要的。当我使用它时,图像(星星)将会消失。 - Utku Soytaş
不,启动并没有消失,背景回到了图片。 - kodamirmo

0

ImageButton是你的更好选择。图片源将会像你说的那样是星星,然后在点击时改变背景。如果想要在其中设置文本

android:drawableTop="@drawable/any_drawable"
android:text="@string/any_text"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接