レイアウトの背景色を初めて動的に変更したいのですが、android の構成ファイルを使用して、そのファイルは assets フォルダーにある必要があります。それは xml ファイルでも何でもかまいません。私を助けてください。
2 に答える
0
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.reflect を使用できますが、config ファイルでは、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) {
}
}
}
}
于 2013-05-14T07:04:43.317 に答える
0
次のように ID をレイアウトに設定した場合:
<LinearLayout android:id="@+id/myLayout">
<LinearLayout/>
次に、次のように onCreate で backGround を設定できます。
myLayout= findViewById(R.id.myLayout);
myLayout.setBackgroundColor(Color.BLUE);
于 2013-05-14T05:08:07.970 に答える