【问题标题】:Setting the background of a Button view in XML makes the button not-clickable在 XML 中设置按钮视图的背景使按钮不可点击
【发布时间】:2011-05-06 08:50:13
【问题描述】:

我在我的 XML 文件中定义了一个按钮。该按钮的工作方式与您所期望的完全一样……直到我在底部添加该行(android:background="drawable/leftarrow1")。然后按钮在 Activity 中不再可点击,但新的背景显示为我想要的。

什么给了?

<Button
    android:id="@+id/switch_left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:background="@drawable/leftarrow1" />

这里是点击代码供参考

Button switchLeft = (Button) findViewById(R.id.switch_left);
switchLeft.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       Log.w(this.getClass().getName(), "clicked left arrow");
    }
});

【问题讨论】:

    标签: java android xml button android-activity


    【解决方案1】:

    嘿伙计,显示带有图像的按钮,有一个 ImageButton 可用。 在 xml 文件中试试这个。

    【讨论】:

    • 他想要自定义背景而不是按钮上的图标。
    • true octavian,但从他的资源文件看来,他最初是在设置背景,因此我建议相同。
    【解决方案2】:

    我的工作完全正常。每次点击都会被记录下来。

    我的猜测是您使用纯图像文件(.png、.jpeg)作为背景。如果您只是使用这样的图像,则在单击或选择时它永远不会改变。为此,有描述here 的状态列表drawable。

    在该 XML 文件中,您可以定义要在特定状态下显示的图像,例如选中、单击等。

    另一个提示。例如,如果您想检查按钮的功能,请使用此类代码。

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class TestButton extends Activity {
    
        Context ctx = null;
        Button btn = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.buttonbackground);
    
            ctx = getApplication();
    
            btn = (Button) findViewById(R.id.switch_left);
    
            btn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                   Toast.makeText(ctx, "Button clicked", 5000).show();
                   // Log.w(this.getClass().getName(), "clicked left arrow");
                }
            });
        }
    }
    

    您将更容易识别事件,因为敬酒消息是一种更直观的反馈。

    【讨论】:

    • 我无法让 Toast 工作...也尝试了 getApplicationContext()。另外,是的,我使用 png/jgp 作为背景。我是否必须实现所有状态列表可绘制对象才能使其正常工作?
    • 注意:我不关心按钮的样子,我关心的是当我点击它时触发的代码......它没有这样做:(
    • @user432209:不,您不必实现状态列表可绘制对象。它只是指向显示背景的更优雅方式的指针,但它与您的问题无关。我已经看到你的第二个问题,你提到你有一个包含日志消息的自定义视图。如果与它有关,请告诉我,以便我回答正确的问题。
    • 呸,我的问题很愚蠢......我有两个按钮使用相同的资源,因此我为相同的资源实现了两个点击方法,这完全搞砸了。感谢您让我找到最终解决方案....但不,我的其他问题没有解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2021-11-13
    相关资源
    最近更新 更多