call the activity interface method onDrawerItemSelected(view,position) in fragment page

时间:2016-04-07 10:36:11

标签: java android android-fragments interface

I need to call the activity interface method onDrawerItemSelected(view,position) in fragment page.is it possible.anyone can help me with this.So that I can do a custom drawer in fragment page.

MainActivity.java:

 public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

@Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    private void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);
        switch (position) {
            case 0:
                fragment = new UserProfileFragment();
                title = getString(R.string.title_discovery);
                break;
            case 1:
                fragment = new SettingsActivity();
                title = getString(R.string.title_messages);
                break;
            case 2:
                fragment = new InboxRequestActivity();
                title = getString(R.string.title_discovery);
                break;
            case 3:

                break;
            default:
                break;
        }

 }

CustomFragment.java:

 public class CustomFragment extends Fragment implements FragmentDrawer.FragmentDrawerListener


  menu_btn_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                mDrawerLayout.openDrawer(GravityCompat.START);





            }
        });

on clicking the menu_btn_click, I need to call the activity interface method onDrawerItemSelected(view,position) in fragment page.

1 个答案:

答案 0 :(得分:0)

您需要覆盖片段中的onDrawerItemSelected(View view, int position)方法并在您的活动中调用它:

@Override
public void onDrawerItemSelected(View view, int position) {
    listener.onDrawerItemSelected(view, position);
}
因此,您需要将活动作为FragmentDrawer.FragmentDrawerListener传递给片段(例如,通过适当的设置者)。

setListener(FragmentDrawer.FragmentDrawerListener listener){
    this.listener = listener;
}