-2

I tried opening a url following some others questions, but the onClick event just restart the app and its not opening the browser. Thx for the help

UPDATE: This works for activities not for fragments.

this is my .xml button

        <ImageButton
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:id="@+id/imageButton2"
            android:background="@drawable/icon"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:onClick="EnterButton"/>

This is my .java with the implemented method.

public void EnterButton(View view) {
Uri uri = Uri.parse("http://www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
Xaloju
  • 195
  • 1
  • 16

4 Answers4

0

Instead of this

Uri uri = Uri.parse("http://www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

just use this

startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));

full code :

public void EnterButton(View view) {
    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.google.com")));
}
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
0

use This code its work Man...

public void EnterButton(View view) {
String url = "http://www.google.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
Nitesh Pareek
  • 362
  • 2
  • 10
0

It is intended to work on activity not on Fragments ,reference :https://stackoverflow.com/a/21192511/3111083

But you can do this on fragment instead.

ImageButton button = (ImageButton) view.findViewById(R.id.imageButton2);
 button.setOnClickListener(new OnClickListener()
   {
             @Override
             public void onClick(View v)
             {
                // do something
             } 
   }); 
Community
  • 1
  • 1
Sunil Sunny
  • 3,949
  • 4
  • 23
  • 53
0

After some tries, this is working for my fragments. The other methods from the interface are not modified.

public class HomeFragment extends Fragment implements View.OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);
        ImageButton b = (ImageButton) v.findViewById(R.id.imageButton2);
        b.setOnClickListener(this);
        return v;
    }

     public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageButton2:
                 String url = "http://www.google.com";
                 Intent intent = new Intent(Intent.ACTION_VIEW);
                 intent.setData(Uri.parse(url));
                 startActivity(intent);
              break;
        }
    }
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
Xaloju
  • 195
  • 1
  • 16