将透明按钮图像和背景颜色设置为按钮

时间:2011-11-14 11:50:30

标签: android button

我有一个带有白色边框且没有标签的透明按钮图像。我想创建一个按钮,它的标签,背景透明图像,并想要动态设置背景颜色。

透明按钮图片:
  enter image description here

在使用标签和背景颜色设置按钮图像后,按钮应如下所示:

enter image description here

我尝试使用FrameLayoutTextViewButton来实现这一点。在framelayout中,第一个孩子将是textview,第二个将是按钮。将透明btn图像设置为按钮和textview将具有必须动态设置的标签和背景颜色。我几乎能够做到这一点,但textview大小应该比按钮图像小一点,这件事我必须动态计算。目前textview背景颜色有时会超出按钮,也不会出现圆形。

xml:

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="15dip" >

    <TextView
        android:layout_height="wrap_content" 
        android:layout_width="wrap_content" 
        android:textSize="20sp" 
        android:textColor="#FFFFFFFF"
        android:id="@+id/btn_bacground"
        android:gravity="center"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dip"
        android:layout_marginRight="1dip"
        android:layout_marginLeft="0dip" />

        <Button 
            android:id="@+id/button_img" 
            android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:background="@drawable/btn_transparent_img"/>

</FrameLayout>

修改 将背景颜色,大小和标签设置为Textview。背景图片到按钮。

buttonClick = (Button) buttonClickFrame.findViewById(R.id.button_img);
buttonBg = (TextView) buttonClickFrame.findViewById(R.id.btn_bacground);
buttonBg.setBackgroundColor(Color.parseColor(BG_COLOR));
buttonBg.setText("Click");
buttonPhone.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_transparent_img));
setBackgroundDimentions(buttonClick, buttonBg);
buttonClick.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        onPhoneClick(v);
    }
});

private void setBackgroundDimentions(Button btn, TextView bckView) {
     final Button mBtn = btw;
     final TextView mBckView = bckView;
     ViewTreeObserver vto = mBtn.getViewTreeObserver();
     vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
             int finalHeight = mBtn.getMeasuredHeight();
             int finalWidth = mBtn.getMeasuredWidth();
             mBckView.setWidth(finalWidth - 14);
             mBckView.setHeight(finalHeight - 15);
             return true;
        }
     });
}

请建议我如何实现这一目标。

1 个答案:

答案 0 :(得分:2)

为什么不使用Image Button。!

像这样:

  <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/btn_transparent_img"
            android:background="#000000"
     />
  • 使用imageButton
  • 将您的透明图片添加为src
  • 根据您的需要更改背景颜色

Refer this link for further help:

相关问题