Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

android - How to open navigation drawer on button click in main fragment?

I have made an app with one activity which uses a navigation drawer to open a number of different fragments. I have the actionbar drawertoggle, but it is not very visible. If I place a button in the onCreateView in my main fragment(the fragment that appears when my app first starts up), how can I get it to open the navigation drawer controlled by my activity?


This seems to work. The answer is much simpler than I thought it would be.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View fragView = inflater.inflate(R.layout.mainmenu, container, false);
    button1 = (Button) fragView.findViewById(R.id.button1);         
    mDrawerLayout = (DrawerLayout)getActivity().findViewById(R.id.drawer_layout);
    mDrawerList = (ListView)getActivity().findViewById(R.id.left_drawer);
    button1.setOnClickListener(this);
    return fragView;
}


@Override
public void onClick(View v) {       

        mDrawerLayout.openDrawer(mDrawerList);          

    }

Thank you for your answers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you need open the slide:

mDrawerLayout.openDrawer(Gravity.LEFT); //Edit Gravity.START need API 14

if you need close the slide

mDrawerLayout.closeDrawer(Gravity.LEFT); //Edit Gravity.START need API 14

EXAMPLE

my mDrawerLayout is instanced here:

mDrawerLayout = (DrawerLayout)findViewById(R.id.my_drawer_layout);

my slide state:

mSlideState=false;

if you need to know the slide menu state (closed, opened). Use this code:

mDrawerLayout.setDrawerListener(new ActionBarDrawerToggle(this, 
    mDrawerLayout, 
    R.drawable.ic_menu_slide,
    0,
    0){
@Override
public void onDrawerClosed(View drawerView) {                       
    super.onDrawerClosed(drawerView);
    mSlideState=false;//is Closed
}
@Override
public void onDrawerOpened(View drawerView) {                       
    super.onDrawerOpened(drawerView);
    mSlideState=true;//is Opened
}});

finally. You can use your click event like this:

public void clickEventSlide(){
if(mSlideState){                
    mDrawerLayout.closeDrawer(Gravity.END);
}else{              
    mDrawerLayout.openDrawer(Gravity.END);
}}

In my case, my slide menu is at the right (Gravity.END), but if you need it on the left, try with Gravity.START


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...