【发布时间】:2013-03-05 14:32:51
【问题描述】:
我有一个按钮,没有任何文字,只有背景颜色。在按钮的onClick() 事件中,我需要设置没有xml 规范的按钮边框。我尝试将渐变矩形形状作为背景drawable 到对我的布局不灵活的按钮。
如何为按钮设置特定颜色的边框?
这是我的代码。
Button btnBlackColor=new Button(this);
int mButtonWidth=100;
btnBlackColor.setWidth(mButtonWidth);
btnBlackColor.setHeight(mButtonWidth);
btnBlackColor.setBackgroundColor(Color.BLACK);
btnBlackColor.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
GradientDrawable btnShape = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]{Color.BLUE,Color.LTGRAY});
btnShape.setCornerRadius(0);
btnShape.setSize(mButtonWidth, mButtonWidth);
btnShape.setBounds(10, 10, mButtonWidth, mButtonWidth);
ClipDrawable btnClip = new ClipDrawable(btnShape, Gravity.LEFT,ClipDrawable.HORIZONTAL);
btnShape = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]{Color.BLACK, Color.DKGRAY});
btnShape.setCornerRadius(0);
btnShape.setSize(mButtonWidth, mButtonWidth);
btnShape.setBounds(5, 5, mButtonWidth, mButtonWidth);
LayerDrawable btnLayer= new LayerDrawable(new Drawable[]{btnShape, btnClip});
btnBlackColor.setBackgroundDrawable(btnLayer);
}
});
【问题讨论】:
-
“我有一个按钮,没有任何文本,只有背景颜色”——这看起来和行为都不像一个按钮,因为使按钮看起来响应点击的原因是它的背景作为
StateListDrawable. -
如何在没有 xml 规范的情况下添加 StateListDrawable?
-
StateListDrawable是一个 Java 类。欢迎您创建它的实例并根据需要配置这些实例。话虽如此,由于大约 99.44% 的StateListDrawable用户通过 XML 进行操作,因此您可能会发现通过 Java 进行管理的示例相对较少。