如何在安卓中更改ImageView的图片来源

50

这是我的 XML,它位于出现在我的活动中的片段内部。

<FrameLayout
                    android:id="@+id/frame1"
                    android:layout_width="wrap_content"
                    android:layout_height="115dp"
                    android:layout_margin="2dp"
                    android:layout_weight="0.33">

                    <ImageView
                        android:id="@+id/whoamiwith"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:scaleType="fitCenter"
                        android:src="@drawable/default_image" />
                </FrameLayout>

这是我的Java代码:

@Override
public void onClick(View click) {
    if (click == profileBtn) {
        whoamiwith.setBackgroundResource(R.drawable.image_i_wanna_put);
    }
}

我正在尝试更改图像视图的图像源。没有语法错误,但是当我点击按钮时,模拟器会强制关闭,并且在日志记录中说:

java.lang.NullPointerException

它指向的那行代码是:

whoamiwith.setBackgroundResource(R.drawable.loginbtn);

你需要检查像 click.getId() == profileBtn 这样的代码。并分享你如何初始化你的 whoamiwith 代码? - Hardik Joshi
您的初始化存在问题,请检查您的ImageView ID。 - Rethinavel
这个强制关闭问题一整天都在困扰我。顺便说一下,<FrameLayout> 位于一个出现在我的活动中的片段上,我认为这可能是其中一个原因。你们觉得呢? - jofftiquez
请展示给我 whoamiwith 的初始化行。 - SweetWisher ツ
你有没有像这样初始化... ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)。它说 whoamiwith 是 null,我想。 - Manivannan
显示剩余5条评论
7个回答

110
whoamiwith.setImageResource(R.drawable.loginbtn);

12
 ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)  
 Drawable new_image= getResources().getDrawable(R.drawable.loginbtn);   
    whoamiwith.setBackgroundDrawable(new_image);

2
setBackgroundDrawable现在不幸已经过时了。 - sk1pro99

6

只是尝试一下

ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)  
whoamiwith.setImageResource(R.id.new_image);

3

初始化图像视图:

whoamiwith = findViewByid(R.id.whoamiwith);

然后在单击方法中,编写以下代码行以更改图像资源:
 if(android.os.Build.VERSION.SDK_INT > 15)
    {
        // for API above 15
        whoamiwith.setBackground(getResources().getDrawable(R.drawable.loginbtn));
    }
    else
    {
        // for API below 15
        whoamiwith.setBackgroundDrawable(getResources().getDrawable(R.drawable.loginbtn));
    }

3
ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith);
whoamiwith.setImageResource(R.drawable.image_i_wanna_put);

枪声响起。哈哈。 - jofftiquez

2

0
在 Kotlin 中,我们可以通过编程的方式像这样改变 ImageView。
val imageView: ImageView = findViewById(R.id.imageView)
imageView.setImageResource(R.drawable.imagename)

而在Java中,

ImageView imageView= (ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.imagename);

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