在按钮顶部叠加图像

时间:2011-05-18 01:22:52

标签: android android-layout

这是我未回答的问题: Add new item count to icon on button - Android

基本上我想在顶部显示“新”计数。我认为它覆盖了现有按钮的一些视图。怎么做到这一点?

2 个答案:

答案 0 :(得分:1)

最简单的事情是:

  1. 使用RelativeLayout,layout_height和layout_width设置为WRAP_CONTENT。
  2. 将一个Button放入RelativeLayout,并将layout_height和layout_width设置为WRAP_CONTENT。
  3. 将ImageView添加到与PARENT_TOP和PARENT_RIGHT对齐的RelativeLayout中,并将可见性设置为GONE。

    然后,您只需将ImageView的drawable设置为适当的计数图像,并将可见性设置为VISIBLE。

答案 1 :(得分:0)

好的,这就是我要做的事情:

创建一个扩展按钮的自定义控件。我不打算为你做漂亮的图形,但这会给你一个基本的想法:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.Button;

    public class CounterButton extends Button{
        protected int count=0;
        protected final Paint myTextPaint = new Paint();
        protected final Paint myCirclePaint = new Paint();

        public CounterButton(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_email));
            this.myCirclePaint.setARGB(150, 255, 0, 0);
            this.myTextPaint.setARGB(150, 255, 255, 255);

        }

        @Override
        protected void onDraw(Canvas canvas) {
                    if(count!=0){
            canvas.drawCircle((float) (this.getWidth()*.75), (float) (this.getHeight()*.4), this.getHeight()/5, myCirclePaint);
            canvas.drawText(Integer.toString(count), (float) (this.getWidth()*.75), (float) (this.getHeight()*.4), this.myTextPaint);
             }
        }
    }

清理您绘制的文本的大小,圆圈定位(并添加边框等),并且您有自定义控件。你可以进一步扩展它,这样你就可以用xml或动态设置背景,并且你有一个带有数字计数器的可重复使用的控件。

然后在你的代码中你可以做到:

CounterButton cb=(CounterButton) findViewById(R.id.whateverYouGaveItInXML);
cb.count=SomeNewNumber;
cb.invalidate;

无效将使用圆圈中的新值重绘图像。

如果你想让它轻松点击,我会使用一个按钮 - 但如果你只是在做一个视图,你可以轻松地扩展视图。

相关问题