我想从我的课堂上创建ImageVIew,但是我有一些例外,不知道为什么。请帮我。
这是我的课
公开课卡{
Bitmap bitmap;
public Card( Bitmap bitmap, LinearLayout linearLayout,Context context){
ImageView imageView=new ImageView(context);
imageView.setImageBitmap(bitmap);
imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.addView(imageView);
}
和
public class MainActivity extends AppCompatActivity {
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.jpg);
Card card;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout=findViewById(R.id.ll);
card=new Card(bitmap,linearLayout,this);
setContentView(R.layout.activity_main);
最佳答案
移动
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.jpg);
onCreate方法中的定义。这应该解决NullPointerException,因为尚未定义上下文。
因此,它应如下所示:
public class MainActivity extends AppCompatActivity {
Bitmap bitmap;
Card card;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.jpg);
LinearLayout linearLayout=findViewById(R.id.ll);
card=new Card(bitmap,linearLayout,this);
....