[英]How do I make a Dialog Box work inside an onClick Listener in a Fragment in Android?
I am trying to build an android app and have come across a situation where I want a user to navigate between Dates by clicking Previous (Month) and Next (Month) buttons. 我正在尝试构建一个Android应用,并且遇到一种情况,我希望用户单击“上一个(月)”和“下一个(月)”按钮在日期之间导航。 I however do not want the user to go to a month after the current month. 但是,我不希望用户在当前月份之后再去一个月。 I would like the App to prompt a dialog letting the user know that they cant select a month after the current. 我希望该应用程序提示一个对话框,让用户知道他们无法选择当前日期之后的一个月。 Below is my code snippet - I am getting an error on two portions 以下是我的代码段-我在两个部分上遇到错误
01. if(formattedDate.before(currentMonth) || formattedDate.equals(currentMonth)){
On the above I am getting an error saying 在上面我得到一个错误的说法
The method before(Calendar) is undefined for the type String
02. new AlertDialog.Builder(HomeFragment.this)
and on the above I am getting an error saying 在上面我得到一个错误的说法
The constructor AlertDialog.Builder(HomeFragment) is undefined
Below is my full code for the on-click listener 以下是点击侦听器的完整代码
NextPicker.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(formattedDate.before(currentMonth) || formattedDate.equals(currentMonth)){
c.add(Calendar.MONTH, 1);
formattedDate = df.format(c.getTime());
Log.v("NEXT DATE : ", formattedDate);
DatePicker.setText(formattedDate);
}
else{
new AlertDialog.Builder(HomeFragment.this)
.setTitle("Wrong Date Selection!")
.setMessage("The Month Selected must be before or equal to current month")
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
});
Your first problem is that formattedDate is a String. 您的第一个问题是formattedDate是一个字符串。 It needs to be a java.util.Date. 它必须是一个java.util.Date。
Your second problem comes from the fact that the AlertDialog.Builder constructor requires a Context sub-class. 您的第二个问题来自AlertDialog.Builder构造函数需要Context子类的事实。 Fragment is not a Context sub-class, but Activity is. Fragment不是Context子类,而Activity是。 Try something like 尝试类似
new AlertDialog.Builder(HomeFragment.this.getActivity());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.