简体   繁体   中英

Android: Placing a bitmap or drawable image into an XML displayed screen

Well after days of looking I come to the source. I have main screen that is drawn and created in Eclipse Graphical layout. It consists of buttons across the top of the screen. Below the buttons is image.png area. On startup of app it displays correctly. Buttons at top and graphic image below the buttons. On pushing each button I want the image to be changed. I can supply either a drawable or bitmap image (figured that out). I need help. What I don't understand is how I get an external image to display with the XML generate screen buttons.

I have currently many test trials but none give me what I am looking for. I want to place either a drawable or bitmap image into R.id.imgVwMain and have it display with the buttons. I know I've got extra code in what is provided. R.id.imgVwMain as a default has an image in it at start up (ie splash screen) but I want to replace it dynamically on button push.

Code snippets:

ImageView img=new ImageView(this);  
View image;
Drawable drawable= getImg(0);   // GETS NEW IMAGE as drawable
img.setImageDrawable(drawable); 

//setContentView(img); // when uncommented displays just the image no buttons, not what needed
//R.id.imgVwMain    // the target ID to place the new image into

image = findViewById(R.id.imgVwMain);

ImageView imageView=(ImageView)findViewById(R.id.imgVwMain);  

imageView.setImageBitmap(drawableToBitmap(drawable));

image.setImageResource(imageView);

setContentView(R.layout.main);  //of course this just displays default of the XML

You can probably use addView to add an imageView dynamically and likewise call removeView to get rid of an imageView. At some point you'll need to set the layout parameters as well. Hopefully this will get you started:

myParentViewOrLayout.removeView(oldImage);

ImageView newImage = (ImageView) findViewById(R.id.imgToAdd);
//Set your layoutParams
myParentViewOrLayout.addView(newImage);

Set onClickListeners onto your buttons like so:

Button mButton = (Button) findViewById(R.id.my_button);
mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ImageView ivImage = (ImageView) findViewById(R.id.imgVwMain);
        ivImage.setImageDrawable(getImg(0));
    }
});

Now, whenever the button is clicked it set's the image of your imageview to whatever you'd like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM