2016-01-10 5 views
2

У меня есть два класса. Один из них - абстрактный класс BaseActivity.java, который расширяет AppcompactActivity, а другой - DrawerFragment.java, который расширяет Fragment! Как создать класс BaseActivity для реализации NavigationItemSelectedListener и обработать события перемещения элемента навигации из этой активности! Я копия вставить соответствующий код ниже:Как установить элемент навигации для навигации NavigationDrawer?

BaseActivity.java

public abstract class BaseActivity extends AppCompatActivity { 
    private static final String TAG = BaseActivity.class.getSimpleName(); 
    protected Toolbar mToolbar; 
    protected DrawerFragment mNavigationDrawerFragment; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(getLayoutResource()); 
     mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar); 
     setSupportActionBar(mToolbar); 
     getSupportActionBar().setDisplayShowHomeEnabled(true); 
     getSupportActionBar().setElevation(0); 


     // Set navigation drawer 
     mNavigationDrawerFragment = (DrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_drawer); 
     mNavigationDrawerFragment.setNavig((DrawerLayout) findViewById(R.id.drawer), mToolbar); 

} 

Выдвижные Fragment.java

public class DrawerFragment extends Fragment{ 

    private NavigationView navigView; 
    private Activity activity; 
    private static final String TAG = "NavigationDrawer"; 
    private DrawerLayout drawerLayout; 
    private TextView fullNameTextView; 
    private ImageView profileImage; 


    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view= inflater.inflate(R.layout.navigation_drawer_fragment, container, false); 
     navigView=(NavigationView)view.findViewById(R.id.main_drawer); 

//  Inflating nav_header layout on top of navigation drawer layout 
     View temp=getActivity().getLayoutInflater().inflate(R.layout.nav_header,navigView,false); 
     navigView.addHeaderView(temp); 
     profileImage= (ImageView) temp.findViewById(R.id.profile_image); 
     fullNameTextView= (TextView) temp.findViewById(R.id.fullNameTextView); 
     return view; 
    } 

    public void setNavig(DrawerLayout drawerLayout, Toolbar toolbar) { 
     ActionBarDrawerToggle drawerToggle=new ActionBarDrawerToggle(activity, drawerLayout,toolbar, R.string.drawer_open, R.string.drawer_close); 
     drawerLayout.setDrawerListener(drawerToggle); 
     drawerToggle.syncState(); 
     this.drawerLayout=drawerLayout; 
    } 

    @Override 
    public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     activity=getActivity(); 

    } 

} 

Я знаю, как реализовать пункт клик слушателя DrawerFragment.java класса и обрабатывать события там. Но это не то, что я ищу. Я намерен сделать то же самое с BaseActivity.java класс

ответ

1
//MAKE A PUBLIC METHOD IN THE NAVIGATION VIEW THAT RETURNS NAVIGATION VIEW 
//in DrawerFragment 
public NavigationView getNav(){ 

    return navView; 
} 


//use that public method from baseactivity.java and set listener on the obtained object 
getNav().setNavigationItemSelectedListener(this); 

, но лучший способ - реализовать прослушиватель в ящике навигации сам фрагмент. потому что он делает навигационную панель полной и развязанной с помощью BaseActivity (или любого другого класса). ИЛИ Вы можете сделать это, как показано ниже. Использование интерфейсного механизма, как показано ниже:

//INSIDE FragmentDrawer 
//Let FragmentDrawer Implement OnItemSelectedListener 

//then you need to override onItemSelected() method 
@Override 
public void OnItemSelected(int pos){ 

    //Call The method implemented on your Activity using interface 
    communicator.displayItem(pos); 

//where communicator has reference to your activity and dispayItem() is implemented method 

} 
Смежные вопросы