从片段失败开始Intent活动 - android

时间:2017-07-11 02:45:38

标签: android android-intent android-activity fragment

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

这是我的代码

MainActivity myactivity = (MainActivity) getActivity();


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

3 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

为什么不在intent类本身上执行activity,而不是从intent执行fragment

例如,

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

这应该有用,无需访问您的activity,因为所有fragment无论如何都位于activity上,而且它已经自己知道它所居住的activity指定了

答案 2 :(得分:0)

上面的答案可能/可能不对,但为了最佳做法,总是允许通过活动进行交易,其中包含各自的 片段。< / p>

利用片段中的接口 onAttach ()拨打随附的活动&amp; ;从活动中,允许另一个活动/片段交易。

示例代码如下所示:

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();
}
}

现在在活动方面:在扩展活动/ AppCompActivity

之后立即添加此项
  

实施MyFragment.AnyInterfaceName

在此之后,只需实施方法&amp;在方法内部,允许使用意图从活动中转移到另一个活动。

注意: 如果您想要启动另一个Activity,请不要忘记调用片段中的接口。简单地称之为:

  

anyInterfaceName.startAnotherActivity();

这可能是一项冗长的工作,但对于最佳实践,它是。

从官方Android网站上查看与活动进行通讯 here

希望它有所帮助!!