0

I have a main, auto-generated class. I'm want to draw the simple ic_launcher png to my image view that I declared in xml.

My main class:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyCanvas can = new MyCanvas(this);
        //ImageView img = (ImageView) findViewById(R.id.imageView1);
        //img.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
    }
}

The class I made:

public class MyCanvas extends View{


    public MyCanvas(Context context) {
        super(context);
        ImageView img = (ImageView) findViewById(R.id.imageView1);
        img.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
    }
}

You will notice I commented out setting the bitmap in my main activity. That is because it was a test. The code works perfectly in the main activity but fails in the other class. I don't know how logCat works, but I see a "null pointer exception." I'm almost positive the error is when I load the ImageView.

I tried this: context.findViewById(R.id.imageView1); to no avail.

Note, the image's id is imageView1.

4

2 回答 2

3

for changing ImageView image from MyCanvas class use MyCanvas class Constructor for sending ImageView instance after initializing it in Activity as:

 public MyCanvas(Context context,ImageView img) {
        super(context);
        img.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), 
                                               R.drawable.ic_launcher));
    }

and send ImageView instance as from Activity :

 setContentView(R.layout.activity_main);
 ImageView img = (ImageView) findViewById(R.id.imageView1);
 MyCanvas can = new MyCanvas(this,img);
于 2013-05-30T18:36:27.193 回答
1

In MyCanvas you are using the View class's findViewById and it searches from that views children, which is not the same as in your activity class.

You could for example find the root layout in the MainActivity 1st and pass it as parameter to the MyCanvas.

于 2013-05-30T18:43:16.150 回答