安卓测试应用程序:Toast不工作

4

我是一名Android的新手,正在尝试创建一个小应用程序。

我的Java文件:

//creating object for imagebutton class
ImageButton mainButton = (ImageButton) findViewById(R.id.imageButtonone);

 //creating onclick listener
mainButton.setOnClickListener(new OnClickListener() {

@Override
    public void onClick(View v) {
    //show message
        Toast toast = Toast.makeText(SkeletonActivity.this, "Button Pressed", Toast.LENGTH_LONG);
        toast.show(); 
    }
});

XML:

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

其中imageButton的id = imageButtonone。

我无法打印“按钮已按下”。 请帮忙!


1
请展示您声明 ImageButton 的 XML 部分。 - freshDroid
1
好词汇新手,很高兴认识新词。 - RajaReddy PolamReddy
<ImageButton android:id="@+id/imageButtonone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/dog8" /> - Vimalnath
Toast.makeText(getBaseContext(), "按钮已按下", Toast.LENGTH_LONG).show(); - Nikunj Patel
4个回答

1

1) 可能你的代码没有到达 onClick 方法。检查一下你的 mainButton 是否为空。

2) 在 Eclipse 菜单中:项目 -> 清理(你的项目)


感谢所有的评论!我会按照步骤回复!再次感谢!:-) - Vimalnath

1
public class Abccls extends Activity implements View.OnClickListener {
    /** Called when the activity is first created. */
    //@Override

        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.Button01);
        btn.setOnClickListener(this);

    }
        public void onClick(View view) {
          if(view == btn)
          Toast.makeText(this, "It is a toast ", Toast.LENGTH_SHORT).show();
        }       
}

1
在setOnClickListener中使用View.OnClickListener。我认为这将解决问题。
 //creating object for imagebutton class
 ImageButton mainButton = (ImageButton) findViewById(R.id.imageButtonone);

//creating onclick listener
 mainButton.setOnClickListener(new **View.OnClickListener()** {

@Override
     public void onClick(View v) {
         //show message
          Toast toast = Toast.makeText(SkeletonActivity.this, "Button Pressed", Toast.LENGTH_LONG).show();
   }

});


你的解决方案并没有解决我的实际问题。 你给出的代码只是对我的代码的替代而已。 不管怎样,谢谢!:-) - Vimalnath

0

检查你的图像按钮是否为空?你有没有收到任何异常?


非常感谢大家,我刚刚清理了我的项目,现在它可以正常工作了 :-) - Vimalnath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接