Android:单击按钮时出现吐司 [英] Android: Have toast appear on button click

查看:190
本文介绍了Android:单击按钮时出现吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触Android,只是熟悉一些常见的东西,但无法掌握onClickListner();我基本上有两个复选框和一个按钮,然后单击按钮,就会显示一个吐司,并说出哪些复选框已选中,哪些复选框未选中。

I'm fairly new to Android and just getting familiarized with the common stuff, but I can't get the hang of the onClickListner(); I basically have two checkboxes and a button and on button click a toast should show up and say which checkboxes are checked and which aren't.

public class ExActivity extends Activity implements View.OnClickListener {
    CheckBox cb;
    CheckBox cb2;
    Button buton;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        cb=(CheckBox) findViewById(R.id.cb);
        cb2=(CheckBox) findViewById(R.id.checkbox);
        buton = (Button)findViewById(R.id.buton);
        buton.setOnClickListener(this);
    }

    public void onClick(View arg0) {
        Toast toast;
        if(cb.isChecked()&&cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Amandoua sunt bifate", Toast.LENGTH_SHORT);
        else if(cb.isChecked()&&!cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Doar prima e bifata", Toast.LENGTH_SHORT);
        else if(!cb.isChecked()&&cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Doar a doua e bifata", Toast.LENGTH_SHORT);
        else if(!cb.isChecked()&&!cb2.isChecked()) toast = Toast.makeText(getApplicationContext(), "Nici una nu e bifata", Toast.LENGTH_SHORT);
    }
}

忽略罗马尼亚变量名称和文本,XML是行。
我也尝试添加如下onClick():

Disregard the romanian variable names and texts and the XML is all right. I also tried to add the onClick() like this:

buton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // my code;
    }
});

但是这个情况更糟。

推荐答案

两种方法都是正确的。在我看来,您只是最后没有吐司。
看起来好像没有执行onClick。

Both ways are correct. It seems to me that you just didn't show the toast in the end. Which can look like the onClick wasn't executed.

添加

if(toast != null) {
    toast.show();
}

到您的onClick()方法的结尾应该可以解决问题。

(空检查,以防万一因为之前没有匹配条件而没有创建Toast实例)

to the end of your onClick() method should do the trick.
(The null check just in case you didn't create a toast instance because no condition was matched before).

这篇关于Android:单击按钮时出现吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆