Get a bitmap from arrays, then load it into the background

Hello to all. I was very helpful here in the past, and I was wondering if you guys could help me with anything.

I would like to load a bitmap from assets, and then add it to the background of the linear layout image that I created in the code. I know how to do this with an xml layout file, but in this case I need to do this in code. I still have it and it works with the .xml layout, but when I try to create a linear layout and ImageView in the code, the image does not appear. There is something that I see or do wrong. here is the code i got

ImageView backgroundPainting = new ImageView(this); backgroundPainting.setAdjustViewBounds(true); LinearLayout rel = new LinearLayout(this); // RelativeLayout backgroundPaintingRL = (RelativeLayout) findViewById(R.id.RelativeLayout01); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); //lp.addRule(RelativeLayout.BELOW, R.id.ButtonRecalculate); //lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); rel.addView(backgroundPainting, lp); // backgroundPainting = (ImageView) findViewById(R.id.backgroundPainting2); getArtist = levelSelect.getArtistNameSelected(); getLevel = level.getLevelSelected() ; String imagePath = "artists-images/"+getArtist + getLevel+".jpg"; try { // Get reference to AssetManager AssetManager mngr = getAssets(); // Create an input stream to read from the asset folder InputStream ins = mngr.open(imagePath); // Convert the input stream into a bitmap levelBitmap = BitmapFactory.decodeStream(ins); backgroundPainting.setImageBitmap(levelBitmap); } catch (final IOException e) { e.printStackTrace(); Toast.makeText(levelView.this, "couldn't set image to background", Toast.LENGTH_LONG).show(); } 

Please help thnx,

Pengume

+4
source share
3 answers

First you must create one linear layout in your XML file. And then access this layout in your code.

 LinearLayout linearMain = (LinearLayout) findViewById(R.id.linearmainLayout); 

Then you try to do the following by adding the last two lines after setting the bitmap to backgroundPainting

 rel.addView(backgroundPainting, lp); linearMain.addView(rel); 

or you can try this way

 setContentView(rel); 

and write one line for the last time after setting the bitmap to backgroundPainting

 rel.addView(backgroundPainting, lp); 
0
source

You must add this view to its parent view, which is created but not added.

0
source

Just use setContentView(rel); after creating LinearLayout

0
source

Source: https://habr.com/ru/post/1340587/


All Articles