为什么getActivity()
在AlertDialog
内返回null?
这是班级
Class A extends Common{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button save = (Button) view.findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
System.out.println("the activity outside dialog.."+getActivity());
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setPositiveButton("Check acitivity",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
dialog.cancel();
System.out.println("the activity inside dialog.."+getActivity());
}
});
}
}
Common类将片段扩展为 -
import android.support.v4.app.Fragment;
Class Common extends Fragment
{
//Some code
}
输出为 -
the activity outside dialog..com.testapp.main.MainActivity@42131080
the activity inside dialog..null
答案 0 :(得分:6)
Activity activity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity=activity;
}
答案 1 :(得分:4)
我认为DialogInterface中的getActivity()指向对话框的上下文
dialog.getActivity()
在DialogInterface中尝试将其更改为:
A.this.getActivity();
编辑:我已经检查了DialogInterface中的getActivity(),它应该可以正常工作。
另一个解决方案可能是使用onAttach回调函数并获取您的活动上下文,以确保您的Fragment在对话框中使用之前附加到父活动。然后使用它而不是getActivity()。
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
yourActivity = activity;
}
答案 2 :(得分:1)
Why the getActivity() is returning null inside AlertDialog ?
那是因为你正在调用DialogInterface.OnClickListener
的getActivity()而不是你的in片段,从而给你null。
<强>溶液强>
A.this.getActivity();
您需要使用this
来调用您班级的引用,并调用方法getActivity()
修改强>
@Override
public void onClick(View v) {
System.out.println("the activity outside dialog.."+getActivity());
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setPositiveButton("Check acitivity",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
System.out.println("the activity inside dialog.."+ A.this.getActivity());
dialog.cancel();
}
});
答案 3 :(得分:1)
将getActivity()替换为A.this
AlertDialog.Builder alert = new AlertDialog.Builder(A.this);
答案 4 :(得分:0)
getActivity()
返回null,直到片段未附加到活动。
你想在onAttach方法调用之后创建对象。
您可以使用onCreateview
方法创建对象以获得最佳实践。
答案 5 :(得分:0)
在Sudhi S和Arash的答案的基础上,我认为这是一个更清晰的选项,在本地处理调用它的方法:
private void showDialog() {
final Activity activity = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setTitle(R.string.my_title)
.setMessage(R.string.my_message)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.e(TAG, "the activity inside dialog... " + activity);
}
});
final AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}