如何在Android上点击ImageView时打开一个URL?

4

如何让 ImageView 链接到网页

我找到了这个链接并将下面的代码复制到 onCreate 函数中和函数外,但它似乎对我没有起作用。以下是我的 main.java 文件:

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

}

这是我的main.xml文件的样子。
<ImageView
            android:id="@+id/logoId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/logo"/>

我做错什么了吗?

我也尝试在main.xml中添加android:onClick="openBrowser",并创建了openBrowser函数,并将所有代码放在那里,超出了onCreate函数,但仍然没有成功。

我还缺少什么?


很遗憾,没有找到。还在寻找中。 - fcukinyahoo
1个回答

4

imageview 标签中添加 android:clickable="true",如下:

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

或者在OnCreate函数中添加img.setClickable(true);

刚才尝试了一下,但似乎并没有起作用,即使可点击的标签看起来是正确的。这个函数是否放在onCreate函数中的正确位置? - fcukinyahoo
我认为这个解决方案是正确的,因为当我在另一个项目上尝试时,你的解决方案起作用了。然而,在我们正在进行生产的项目中,我正在更改activity_main.xml文件,在Android Studio的预览中我可以看到更改,但是当我在Android VM上运行应用程序时,它们没有显示出来。现在正在研究并尝试查看发生了什么。 - fcukinyahoo
请尝试从Android虚拟机中删除现有的项目应用,并清除/删除项目中的“bin”、“gen”文件夹。 - Giru Bhai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接