TLDR:如何在Fragment中显示AlertDialog?
我创建了一个导航抽屉,随我的主页打开,该主页被写为片段。在此主页片段中创建按钮时,该按钮不会按预期显示AlertDialog。我的logcat中没有错误,所以我不确定代码的问题是什么。
MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
displaySelectedPage(R.id.fragment_homepage);
}
public boolean onOptionsItemSelected(MenuItem menuitem) {
switch(menuitem.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(menuitem);
}
private void displaySelectedPage(int itemid) {
Fragment fragment = null;
switch (itemid) {
case R.id.fragment_homepage:
fragment = new Homepage();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedPage(item.getItemId());
return true;
}
}
我认为问题在于使用AlertDialog构建器声明getActivity,主页:
public class Homepage extends Fragment {
private AlertDialog mAlertDialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
Button aboutButton = (Button) v.findViewById(R.id.about_button);
aboutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("About");
builder.setMessage("Chameleon is the app for you");
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
mAlertDialog = builder.show();
}
});
return inflater.inflate(R.layout.fragment_home, container, false);
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Homepage");
}
}
编辑:在onCreateView中用return v替换return语句修复了问题