简体   繁体   中英

How to change the background color for layouts using configuration file in android

I want to change the background color for layouts dynamically for the first time only, using configuration file in android that file should be in assets folder,it can be xml file or anything. please help me.

If you set an ID to your layout as follows :

<LinearLayout android:id="@+id/myLayout">
<LinearLayout/>

Then you can set your backGround in onCreate like this:

myLayout= findViewById(R.id.myLayout);
myLayout.setBackgroundColor(Color.BLUE);

1.use color for int value. in the assets file config.txt, you can input color for int value like this. for example this value is Color.RED

4294901760

2.use this code in your appliaction

        String config = "config.txt";
    InputStream is = null;
    try {
        is = getAssets().open(config);
        DataInputStream dis = new DataInputStream(is);
        String color = dis.readUTF();
        ColorDrawable drawable = new ColorDrawable(Integer.parseInt(color));
        //use drawable
        //for example
        new TextView(this).setBackgroundColor(Integer.parseInt(color));
        new TextView(this).setBackgroundDrawable(drawable);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(is != null)
        {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

3.you can use reflect, but in the config file, write the color name from values/colors.xml.

        String config = "config.txt";
    InputStream is = null;
    try {
        is = getAssets().open(config);
        DataInputStream dis = new DataInputStream(is);
        String color = dis.readUTF();

        try {
            Field field = R.color.class.getDeclaredField(color);
            field.setAccessible(true);
            Integer id = (Integer) field.get(null);

            ColorDrawable drawable = new ColorDrawable(getResources().getColor(id));
            // use drawable
            // for example
            new TextView(this).setBackgroundColor(getResources().getColor(id));
            new TextView(this).setBackgroundDrawable(drawable);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
}

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