47

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

6 回答 6

105
whoamiwith.setImageResource(R.drawable.loginbtn);
于 2013-10-23T07:50:09.417 回答
12
 ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)  
 Drawable new_image= getResources().getDrawable(R.drawable.loginbtn);   
    whoamiwith.setBackgroundDrawable(new_image);
于 2013-10-23T08:33:37.980 回答
5

你试一试

ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)  
whoamiwith.setImageResource(R.id.new_image);
于 2013-10-23T08:35:04.930 回答
3

初始化图像视图:

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));
    }
于 2013-10-23T08:19:34.550 回答
3
ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith);
whoamiwith.setImageResource(R.drawable.image_i_wanna_put);
于 2013-10-23T08:40:07.563 回答
2

异常whoamiwith为空。你初始化了whoamiwith吗,ImageView whoamiwith = (ImageView)findViewById(R.id.whoamiwith)

请参阅动态使用 setImageDrawable 在 ImageView 中设置图像

于 2013-10-23T08:26:06.380 回答