如何从Android中的片段启动浏览器活动

时间:2015-04-20 16:38:11

标签: android android-intent fragment

我想从我的片段中打开浏览器 但是当我启动我的应用程序时它会崩溃 怎么了?

public class C_spider extends Fragment {

Button btn_off2;

public C_spider() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view=  inflater.inflate(R.layout.fragment_cspider, container, false);

    btn_off2 = (Button)view.findViewById(R.id.btn_off2);
    btn_off2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse("https://www.google.com"));
            getActivity().startActivity(i);

        }
    });

    return view;
}

}

1 个答案:

答案 0 :(得分:2)

尝试将您的代码放入onActivityCreated()

public class C_spider extends Fragment {

    Button btn_off2;

    public C_spider() {
     // Required empty public constructor
    }

    @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {
         // Inflate the layout for this fragment
         View view=  inflater.inflate(R.layout.fragment_cspider, container,   false);  
        return view;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        btn_off2 = (Button)getActivity().findViewById(R.id.btn_off2);
        btn_off2.setOnClickListener(new View.OnClickListener() {
       @Override
        public void onClick(View v) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse("https://www.google.com"));
            getActivity().startActivity(i);

            }
        });

    }

 }