How to open url when clicking on ImageView on Android?

How to link ImageView to a web page

I found this link and I copied the code below into the onCreate function and outside the onCreate function, and this does not seem to work for me. Below is my main.java file

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       // Go to myurl.com when clicking on logo
       ImageView img = (ImageView)findViewById(R.id.logoId);

       img.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse("http://casidiablo.net"));
            startActivity(intent);
        }
    });

}

and this is what my main.xml looks like

<ImageView
            android:id="@+id/logoId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/logo"/>

So where am I doing wrong?

I also tried adding android: onClick = "openBrowser" to main.xml, and I created the openBrowser function and put all the code there from the onCreate function and still no luck.

What am I missing?

+4
source share
1 answer

add android:clickable="true"to tag imageviewas

<ImageView
            android:id="@+id/logoId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:src="@drawable/logo"/>

Or add this function img.setClickable(true);toOnCreate

+4

Source: https://habr.com/ru/post/1545881/


All Articles