我可以将Click Listener添加到自定义Toast

时间:2014-02-20 16:04:08

标签: android onclicklistener toast buttonclick android-toast

我正在为我的应用程序创建自定义Toast。我需要的是在Toast上添加的按钮上添加OnClickListener。一切顺利,我可以看到按钮,但它不响应OnClick。任何想法。

示例代码:

Button button = new Button(getApplicationContext());
            button.setText("Click Me");
            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ProgressDialog.show(getApplicationContext(), "Hello", "nothing");

                }
            });
        button.setLayoutParams(new     ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.setMargin(0,-80);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(button);  
        toast.show();

此外,我尝试将onTouchListener添加到这样的按钮。

 button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ProgressDialog.show(getApplicationContext(), "Hello", "nothing");
        return false;
    }
});

但它也不起作用。

2 个答案:

答案 0 :(得分:1)

您不应在Button中加入Toast。只需显示按钮,然后在一段时间后隐藏它。您可以在现有布局的顶部添加RelativeLayout来完成此操作。这样的事情应该有效:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <include layout="@layout/main" /><!-- References your existing layout file -->
    <Button 
        android:id="@+id/toast_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:visibility="gone"
        android:text="@string/click_me"
        android:onClick="showDialog" /><!-- Should reference a String resource "click me"-->
</RelativeLayout>

现在创建 Toast 效果,将以下方法添加到Activity

public void showDialog(View v) {
    if (v.getId() == R.id.toast_button) {
        ProgressDialog.show(this, "Hello", "nothing");
    }
}

然后在onCreate中,显示按钮,如 a Toast

final Button b = (Button) findViewById(R.id.toast_button);
//optionally add some animations for fading in
b.setVisibility(View.VISIBLE);
Timer t = new Timer();
t.schedule(new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //optionally add some animations for fading out
                b.setVisibility(View.GONE);
            }
        });
    }
}, 1000);

答案 1 :(得分:0)

Crouton图书馆解决了这个问题。希望它对其他人也有帮助。

https://github.com/keyboardsurfer/Crouton