[英]How To Set Image Bitmap From External Class?
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.
我想将简单的ic_launcher png绘制到我在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.
该代码在main活动中工作完美,但在其他类中失败。 I don't know how logCat works, but I see a "null pointer exception."
我不知道logCat的工作原理,但是我看到“空指针异常”。 I'm almost positive the error is when I load the ImageView.
我几乎肯定是错误是当我加载ImageView时。
I tried this: context.findViewById(R.id.imageView1); 我尝试了这个:context.findViewById(R.id.imageView1); to no avail.
无济于事。
Note, the image's id is imageView1. 请注意,图像的ID为imageView1。
for changing ImageView image from MyCanvas
class use MyCanvas class Constructor for sending ImageView
instance after initializing it in Activity as: 要从
MyCanvas
类更改ImageView图像, MyCanvas
使用MyCanvas类构造函数在Activity中将ImageView
实例初始化为后发送ImageView
实例:
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 : 并从Activity发送ImageView实例:
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.id.imageView1);
MyCanvas can = new MyCanvas(this,img);
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. 在MyCanvas中,您使用的是View类的findViewById,它从该视图子级中搜索,这与您的活动类不同。
You could for example find the root layout in the MainActivity 1st and pass it as parameter to the MyCanvas. 例如,您可以在MainActivity 1st中找到根布局,并将其作为参数传递给MyCanvas。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.