如何在android中更改ImageView源代码

时间:2013-10-23 07:35:15

标签: java android xml android-imageview

这是我的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);
    }
}

我正在尝试更改图像视图的图像源。没有语法错误但是当我单击按钮时,模拟器正在给我一个强制关闭,并且在logcat上它说:

  

显示java.lang.NullPointerException

它指向了这一行:

whoamiwith.setBackgroundResource(R.drawable.loginbtn);

6 个答案:

答案 0 :(得分:54)

whoamiwith.setImageResource(R.drawable.loginbtn);

答案 1 :(得分:9)

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

答案 2 :(得分:3)

试试

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

答案 3 :(得分:1)

初始化图片视图:

whoamiwith = findViewByid(R.id.whoamiwith);

然后在Click方法上,写下这一行来更改图像资源:

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

答案 4 :(得分:1)

异常whoamiwith为空。 你初次化whoamiwith喜欢, ImageView whoamiwith =(ImageView)findViewById(R.id.whoamiwith)

参考Using setImageDrawable dynamically to set image in an ImageView

答案 5 :(得分:1)

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