我想使用Firebase在ChatListAdapter类的mainActivity中弹出警报视图。
问题/错误:
com.firebase.androidchat.Main.activity.this无法从静态上下文中引用
ChatListAdapter中的代码:
public class ChatListAdapter extends FirebaseListAdapter<Chat> {
...
protected void populateView(View view, Chat chat) {
...
MainActivity.displayAmountPopup();
}
ChatListAdapter中的代码:
public static void displayAmountPopup(){
....
new AlertDialog.Builder(MainActivity.this)
.setTitle(strTitle)
.setMessage(strAmountMessage)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Positive");
// Present Acknowledgement View!!!!!!!!!
Intent intent = new Intent(MainActivity.this, AcknowledgementActivity.class);
startActivity(intent);
/*Couldn't work this Error:local variable mContext is accessed from within inner class; needs to be declared final
Intent intent = new Intent(mContext, AcknowledgementActivity.class);
//startActivity(intent);
mContext.startActivity(new Intent(mContext, AcknowledgementActivity.class));*/
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Negative");
}
})
.show();
}
答案 0 :(得分:2)
com.firebase.androidchat.Main.activity.this无法从静态上下文中引用
因为无法从MainActivity.this
方法/块访问static
。
要获取显示AlertDialog
的上下文,请向displayAmountPopup
方法添加一个Context参数:
public static void displayAmountPopup(Context mContext){
....
new AlertDialog.Builder(mContext)
....
}
现在,在从displayAmountPopup
调用时,将上下文传递给populateView
方法:
MainActivity.displayAmountPopup(view.getContext());
答案 1 :(得分:0)
您可以在对话框中使用上下文 和强制转换活动以启动Intent
Intent intent = new Intent(context, AcknowledgementActivity.class);
((Activity) context).startActivity(intent)
来自评论代码
public static void displayAmountPopup(Context context){
....
new AlertDialog.Builder(context)
.setTitle(strTitle)
.setMessage(strAmountMessage)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Positive");
// Present Acknowledgement View
//Intent intent = new Intent(context, AcknowledgementActivity.class);
//startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("AlertDialog", "Negative");
}
})
.show();
}