【问题标题】:Start Intent activity from fragment fail - android从片段失败启动 Intent 活动 - android
【发布时间】:2017-07-11 02:45:37
【问题描述】:

我想从片段开始活动但失败了。

这是我的代码

MainActivity myactivity = (MainActivity) getActivity();


Intent intent = new Intent(myactivity, PopUpImageActivity.class);
Bundle extras = new Bundle();
myactivity.startMyIntent(intent);

【问题讨论】:

    标签: android android-intent android-activity fragment


    【解决方案1】:

    试试这个:

        startActivity(new Intent(getActivity().getApplicationContext(), YourActivity.class));
    

    【讨论】:

      【解决方案2】:

      与其在activity 中执行intent,不如在fragment 类本身上执行intent

      例如,

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

      这应该可以工作,并且无需访问您的activity,因为无论如何所有fragment 都驻留在activity 上,并且它自己已经知道它驻留在哪个activity 上而没有指定它

      【讨论】:

        【解决方案3】:

        上面的答案可能/可能不正确,但最佳实践始终允许通过包含各自 FragmentActivity进行交易。

        在你的 Fragment 中使用 interfacesonAttach() 来调用封闭的 Activity 和从活动中,允许另一个活动/片段事务。

        示例代码如下所示:

        public class MyFragmentExample extends Fragment{
        
        //Creating instance of Interface
        AnyInterfaceName anyInterfaceName;
        
        
        /*
        This onAttach is responsible for attaching the interface
        listener of fragment to Activity
        */
         @Override
            public void onAttach(Context context) {
                super.onAttach(context);
                try {
                    anyInterfaceName = (AnyInterfaceName) context;
                } catch (ClassCastException ex) {
                    throw new ClassCastException(ex.getMessage() + "must implement AnyInterfaceName");
                }
            }
        
         @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                // Inflate the layout for this fragment
                return view;
            }
        
        
        // Define an interface with any name
        public interface AnyInterfaceName{
            /*
              you can give any name to this function & this
              function will be implemented later in activity
            */
            void startAnotherActivity();
        }
        }
        

        现在在 Activity 方面:在 extends Activity/AppCompActivity

        之后添加它

        实现 MyFragment.AnyInterfaceName

        在此之后,只需在方法内实现 方法 &,允许在使用 Intent 从 Activity 中转换到另一个 Activity。

        注意: 当您想要启动另一个活动时,不要忘记调用片段中的接口。简单地这样称呼它:

        anyInterfaceName.startAnotherActivity();

        这可能是一项漫长的工作,但为了最佳实践,确实如此。

        从官方 android 网站查看 与 Activity 通信 here

        希望对你有帮助!!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多