从 Fragment 开始一个新的 Activity [英] Start a new Activity from Fragment

查看:25
本文介绍了从 Fragment 开始一个新的 Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Android Studio,我有一个带有占位符片段的 MainActiviy 类.这个片段有按钮,但必须加载一个活动.如何做到这一点?有人告诉我尝试类似下面的方法,但新的 Intent 不起作用.

Using Android Studio, I have my MainActiviy class with a Placeholder fragment. This fragment has buttons, but one has to load an Activity. How does one do this? I was told to try something like the below, but the new Intent does not work.

Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          Intent intent = new Intent(MainActivity.class, AnotherActivity.class);
          startActivity(intent);
        }
 });

推荐答案

如果你看看 文档 您可以看到,要开始一项活动,您需要使用以下代码

If you have a look at the documentation you can see that to start an activity you'll want to use the following code

Intent intent = new Intent(getActivity(), AnotherActivity.class);
startActivity(intent);

目前您在需要上下文对象的地方使用 MainActivity.class.如果您当前正在参与一项活动,只需传递 this 就足够了.片段可以通过 getActivity() 函数获取活动.

Currently you're using MainActivity.class in a place that requires a context object. If you're currently in an activity, just passing this is enough. A fragment can get the activity via the getActivity() function.

你上面的完整代码应该是这样的

Your full code above should look like this

Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(getActivity(), AnotherActivity.class);
        startActivity(intent);
    }
});

这篇关于从 Fragment 开始一个新的 Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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