我在主要活动中使用导航抽屉定义为
private DrawerLayout drawerlayout;
我在主要活动中使用它来打开和关闭我的导航片段,但导航片段类中有3个特定按钮,我想使用导航片段功能drawerlayout.closedrawer(r.id.drawer)
但是每当我在nav片段类中再次定义它并尝试在onclick中为这些按钮添加它时,单击按钮时,应用程序会因为空指针异常而崩溃。我如何去做同样的事情?
谢谢! 这是我的应用程序中的示例代码: public class navfragment扩展了片段{
public interface OnCloseDrawerListener
{
void onCloseDrawer();
}
@Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.button_logout:
final DialogFragment dialog = new LogoutCancelSignoutDialogFragment(mLogoutListener);
dialog.show(getActivity().getSupportFragmentManager(), AbsBaseaActivity.TAG_LOGOUT_DIALOG);
BangoHelper.eventLogout();
((OnCloseDrawerListener)getActivity()).onCloseDrawer();
break;
}
}
在我的班级MainActivity:
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
private DrawerLayout drawerLayout;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//----------Code for Navigation Drawer setup
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close){
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
// getActionBar().setTitle(NavigationPanelFragment.activeFragmentTitle);
// invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// getActionBar().setTitle(NavigationPanelFragment.activeFragmentTitle);
// invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
public void onCloseDrawer()
{
drawerLayout.closeDrawer(R.id.drawer);
}
Even after modifying the code as per the given suggestion it crashes when I click on the button defined onclick for the fragment class, any clue?
答案 0 :(得分:5)
您可以将片段中的回调添加到活动中以关闭抽屉..
实施例
public class YourFragment extends Fragment
{
public void onClick(View v)
{
((OnCloseDrawerListener)getActivity()).onCloseDrawer();
}
public interface OnCloseDrawerListener
{
void onCloseDrawer();
}
}
然后在您的活动中,您需要实现此界面
public class MyActivity extends Activity implements OnCloseDrawerListener
{
@Override
public void onCloseDrawer()
{
// add whatever code you need to close the drawer
}
}
显然,您可以将此界面命名为更准确地表示您需求的内容,并将其传递给您需要的任何参数