单击后如何按下按钮?

Nik*_*tas 34 android pressed button

可能重复:
Android.在按钮创建的操作完成之前,如何将按钮显示为PRESSED?

我有一个按钮,我希望当我按下它时,它会保持按下状态(Froyo上的绿色).

有帮助吗?

mycodes_Button = (Button) findViewById(R.id.mycodes);
...
if (saved_Button.isPressed())
{
    saved_Button.setFocusable(true);
}
Run Code Online (Sandbox Code Playgroud)

像这样的东西?

bee*_*tra 45

我有一个带有自定义背景的按钮,并最终使用所选状态.该状态适用于所有视图.

要使用此功能,您必须将自定义按钮背景定义为状态列表:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_selected="false" android:state_focused="false" 
     android:state_pressed="false"><bitmap ... /></item>
  <item android:state_selected="true"><bitmap ... /></item>
  <item android:state_focused="true"><bitmap ... /></item>
  <item android:state_pressed="true"><bitmap ... /></item>
</selector>
Run Code Online (Sandbox Code Playgroud)

然后使用该背景,假设它/res/drawable/button_bg.xml在您的布局文件中,您使用:

...
<Button android:background="@drawable/button_bg" ... />
...
Run Code Online (Sandbox Code Playgroud)

在您的代码中,您可以切换到onClick侦听器中的(取消)选定状态:

myButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    v.setSelected(true);
    // normal click action here
  }
});
Run Code Online (Sandbox Code Playgroud)

激活状态的本意相匹配较好,但仅适用于Android 3.x和更高.

  • 谢谢beetstra.我注意到了`press`解决方案中的一个缺陷,所以我使用了你的.到目前为止更容易和完美. (2认同)

Ven*_*ddy 38

使用以下代码.这很有用.

mycodes_Button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mycodes_Button.setPressed(true);
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 这基本上有效,但你应该提到,你失去了正常的按钮功能.因为你在这里返回`true`,所以`onClick`东西永远不会被执行.所以实际上你必须触发这些东西,你希望按钮在这个`onTouch`方法中做.顺便说一句:你应该使用`v.setPressed(true)`. (13认同)

kgi*_*kis 5

将一个切换按钮满足您的需求?

从您的评论来看,您似乎并不了解触摸模式。在此模式下,触摸模式是大多数事情的默认设置,它没有重点(这是您要实现的目标),也没有选定的项目。

您可以尝试以编程方式退出触摸模式,但我不建议这样做。经过一小段时间适应后,触摸模式将为用户带来更好的体验。


归档时间:

查看次数:

57664 次

最近记录:

7 年,7 月 前