2014-02-20 87 views
2

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

例如代码:

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; 
    } 
}); 

但它也不起作用。

+1

,而不是烤面包用一个对话框 – Raghunandan

+0

视图不会点击的内部吐司所以使用AlertDialog或popupwindow。 –

+0

使用烤面包上的按钮是个不错的主意。使用对话框 – JesusS

回答

1

您不应该在Toast中包含Button。只需显示按钮,然后在一段时间后隐藏它。您可以通过在现有布局上添加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> 

现在创建吐司效果,添加下面的方法到您Activity:在onCreate

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

然后,显示按钮一个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); 
+0

Phil并非如此。按钮不会收到点击事件。 – Adnan

+0

@Adnan看到我修改后的答案 – Phil

相关问题