Android - 如何在构造函数中传递位图?

Android - How to pass a Bitmap in a constractor?

已编辑

我有这个class:

    public class Item {

        private Bitmap image;

        public Item(Bitmap image) {
            this.image = image;
        }

我也有主activity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //the question is about this line
        Item item = new Item(???);

    }
}

如何从MainActivity中调用Item的构造函数(在onCreate中)?我不知道如何从资源中引用位图。

我要传递给构造函数的图像位于: app >> res >> mipmap >> cat.png

在这里你可以将位图转换为drawable

Drawable myDrawable = getResources().getDrawable(R.drawable.cat);
Bitmap bitmap= ((BitmapDrawable) myDrawable).getBitmap();

在 java 中,您可以通过构建 class 的实例来调用构造函数。

在你的问题中:

new Item(bitmap);

您可以通过这样做在 Activity 中引用资源位图:

Bitmap bitmap = BitmapFactory.decodeResource(getResources() , R.drawable.cat);

在片段中:

Bitmap bitmap = BitmapFactory.decodeResource(getAvtivity().getResources() , R.drawable.cat);
Bitmap image = BitmapFactory.decodeResource(getResources() , R.drawable.cat);