在iOS中,如果我将按钮的背景设置为图像,当我按下按钮时,按钮的全部内容(包括文本)将被遮蔽。我可以在Android中获得相同的效果,还是必须针对不同的状态使用不同的图像?另外,即使我为不同的状态使用不同的图像,我如何让文字也被遮蔽?一个肮脏的方法是将OnClickListener
设置为按钮,并按下时以编程方式遮蔽文本,但还有其他方法吗?按下时自动更改按钮背景和文字外观(如iOS)?
5
A
回答
7
我一直在尝试为此找到一个解决方案,但无法找到任何东西,所以我想出了一个漂亮的解决方案,它适用于所有图像按钮。就像iOS一样。
创建一个黑色,10%透明图像并将其保存为PNG。我称之为button_pressed.png。您可以使用此图片,http://img84.imageshack.us/img84/7924/buttonpressed.png
创建一个名为相关绘制的东西,我把它叫做“button_pressed_layout.xml”
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android=" http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> </selector>
现在摆在你的LinearLayout按钮图像,然后将按钮的的LinearLayout内。在按钮中使用button_pressed_layout.xml作为背景。
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/button_image"> <Button android:id="@+id/myButtonId" android:text="@string/Continue" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/button_pressed_layout" android:textColor="#FFF" android:textSize="16dp" > </Button> </LinearLayout>
That's吧!
0
2
为了在不创建第二个按钮图像的情况下获得按下状态,我创建了一个OnTouchListener来更改按钮的alpha。这不是最美丽的按下状态,但会产生有效的自动行为。
public class PressedStateOnTouchListener implements OnTouchListener
{
PressedStateOnTouchListener(float alphaNormal)
{
mAlphaNormal = alphaNormal;
}
public boolean onTouch(View theView, MotionEvent motionEvent)
{
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
theView.setAlpha(mAlphaNormal/2.0f);
break;
case MotionEvent.ACTION_UP:
theView.setAlpha(mAlphaNormal);
break;
}
// return false because I still want this to bubble off into an onClick
return false;
}
private float mAlphaNormal;
}
在你的活动,适用本听者每一个按钮:
Button theButton = (Button)findViewById(R.id.my_button_id);
theButton.setOnTouchListener(new PressedStateOnTouchListener(theButton.getAlpha()));
+0
这给出了按下状态的“相反”。您应该将图像变暗以显示按下,而不是变亮。并在白色的背景,这减轻了它。 – dacopenhagen 2014-03-03 21:50:33
它是一个切换按钮,其中状态可以是向上或向下,或常规按钮它才会出现不同,因为它是被点击? – TomHarrigan 2011-06-16 23:50:57
这是一个常规按钮。 – hzxu 2011-06-17 00:24:54