将(打开/关闭)按钮添加到(打开/关闭)导航抽屉的活动 [英] Add (open/close) button to activity for (opening/closing) the navigation drawer

查看:43
本文介绍了将(打开/关闭)按钮添加到(打开/关闭)导航抽屉的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从 android 站点学习导航抽屉,我正在使用他们的示例 http://developer.android.com/training/implementing-navigation/nav-drawer.html

I am currently learning about the Navigation Drawer from the android site, and I am using their example http://developer.android.com/training/implementing-navigation/nav-drawer.html

我想要的是在 MainActivity 中添加一个按钮,它可以打开 NavigationDrawer.我需要以编程方式而不是在 XML 中进行.我该怎么做?

What I want is to add a button in the MainActivity which would be able to open the NavigationDrawer. I need to do it programmatically, not in XML. How can I do that?

推荐答案

在包含 drawerLayout 的 MainActivity 中创建一个方法.

Create a method in MainActivity which contains your drawerLayout.

public void open()
{
    mDrawerLayout.openDrawer(Gravity.LEFT);
}


从你的片段在 oncreateView() 方法中,根据您的需要,在您的根膨胀布局中以编程方式添加新按钮.您的片段有按钮
波纹管我修改片段尝试


and from Your fragment In oncreateView() method As you want new Button Programmatically add Button in Your Root inflated layout. Your fragment has button
bellow I modified fragment try

 public static class PlanetFragment extends Fragment {
    public static final String ARG_PLANET_NUMBER = "planet_number";

    public PlanetFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
        int i = getArguments().getInt(ARG_PLANET_NUMBER);
        String planet = getResources().getStringArray(R.array.planets_array)[i];

        int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                        "drawable", getActivity().getPackageName());
        ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
        getActivity().setTitle(planet);
        RelativeLayout root=(RelativeLayout)rootView.findViewById(R.id.root);
        Button button=new Button(getActivity());            
        LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        button.setLayoutParams(params);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        button.setText("openDrawer");
        root.addView(button);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                ((MainActivity)getActivity()).open();
            }
        });
        return rootView;
    }
    }
 }


你可以在你的片段中试试这个代码..


You can try this code in your fragment..

这篇关于将(打开/关闭)按钮添加到(打开/关闭)导航抽屉的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆