I want to set an image saved on sd card in main layout background through my application

后端 未结 1 1272
清酒与你
清酒与你 2020-12-15 01:40

i am creating an application in which i want set different background images in main xml linearlayout.I have stored 5 image files on sd card .now i want to select a pic and

1条回答
  •  执笔经年
    2020-12-15 02:07

    First assign an id to the main xml linearlayout, for example in the following case it is named" container"

        
    
    
        
    
    

    Then in the .java code you can find the layout object and set a drawable as its background:

    package org.example.app;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    
    public class Main extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            String pathName = "/sdcard/gif001.gif";
            Resources res = getResources();
            Bitmap bitmap = BitmapFactory.decodeFile(pathName);
            BitmapDrawable bd = new BitmapDrawable(res, bitmap);
            View view = findViewById(R.id.container);
            view.setBackgroundDrawable(bd);
        }
    }
    

    Regards

    Ziteng Chen

    0 讨论(0)
提交回复
热议问题