簡體   English   中英

如何使用Android中的配置文件更改布局的背景色

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

我只想第一次動態更改布局的背景色,使用android中的配置文件,該文件應位於Assets文件夾中,可以是xml文件或其他任何文件。 請幫我。

如果您按如下方式為布局設置ID:

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

然后,您可以像這樣在onCreate中設置backGround:

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

1.使用顏色作為int值。 在資產文件config.txt中,您可以像這樣為int值輸入顏色。 例如,此值為Color.RED

4294901760

2.在您的應用中使用此代碼

        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.您可以使用反射,但是在配置文件中,從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) {
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM