【问题标题】:Eclipse ADT troubles with (image)button(图像)按钮的 Eclipse ADT 问题
【发布时间】:2014-02-05 09:45:27
【问题描述】:

我想知道我的 Android 开发工具出了什么问题。我可以在布局上添加ButtonImageButton,但稍后在我的代码中我无法添加

myButton.setOnClickListener(new OnClickListener) { ...

我尝试测试设备上的按钮,但遇到异常并且我的程序终止。如果我添加自己的ImageButton 或者我是否使用具有默认设置的预定义 ADT 按钮也没关系。

欢迎任何帮助!

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/btn_unlocked" />

</LinearLayout>

MainActivity.java:

public class MainActivity extends Activity { 

ImageButton lock1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lock1 = (ImageButton) findViewById(R.drawable.btn_unlocked);

    lock1.setOnClickListener(new View.OnClickListener() {   
        @Override
        public void onClick(View v) {
            finish();
        }
    }); 
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

【问题讨论】:

  • 您能否发布您的 logcat 以及您已将哪个 OnClickListener 导入您的班级?
  • 发布您的代码并添加 Logcat !
  • 请将代码编辑到您的问题中。如果没有实际的 Java 代码和异常详细信息,就无法提供帮助。

标签: android eclipse button adt imagebutton


【解决方案1】:

您正在尝试将Drawable 放入您的ImageButton 变量中。这不是正确的方法,您可能已经通过方法名称猜到了:findViewBy**Id**()

您需要将视图的ID 传递给Android,以便它能够从xml 检索它(嗯,不是从xml,但您明白了)。尽管您没有发布 logcat 错误输出,但我会假设您的程序死于 NullPointerException

这是因为如果findViewById() 没有为给定的 id 找到View,它将返回null,就像你可以read here一样。然后,您的程序将在 .setOnClickListener() 行终止,因为您在空对象上调用了方法调用。

长话短说:编辑这一行:

lock1 = (ImageButton) findViewById(R.drawable.btn_unlocked);

看起来像这样:

lock1 = (ImageButton) findViewById(R.id.imageButton1);

【讨论】:

  • 非常感谢您的解释。这解决了我的问题! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
相关资源
最近更新 更多