Skip to content

Instantly share code, notes, and snippets.

@georgioupanayiotis
Last active August 29, 2015 14:16
Show Gist options
  • Save georgioupanayiotis/5c097b320dcdd8b0d26b to your computer and use it in GitHub Desktop.
Save georgioupanayiotis/5c097b320dcdd8b0d26b to your computer and use it in GitHub Desktop.
Load resources from XML in Android
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="resicon">
<item>@android:drawable/ic_dialog_alert</item>
<item>@android:drawable/ic_menu_camera</item>
<item>@android:drawable/ic_menu_compass</item>
<item>@android:drawable/ic_menu_directions</item>
<item>@android:drawable/ic_menu_gallery</item>
</array>
<array name="rescolor">
<item>#FF101010</item>
<item>#FF202020</item>
<item>#FF303030</item>
<item>#FF404040</item>
<item>#FF505050</item>
</array>
</resources>
package com.panayiotisgeorgiou.androidxmlresources
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.content.res.TypedArray;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TypedArray arrayResources = getResources().obtainTypedArray(R.array.resicon);
TypedArray arrayColors = getResources().obtainTypedArray(R.array.rescolor);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(params);
for(int i=0; i<arrayResources.length(); i++){
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(arrayResources.getDrawable(i));
imageView.setBackgroundColor(arrayColors.getColor(i, 0xFF000000));
layout.addView(imageView);
}
setContentView(layout);
arrayResources.recycle();
arrayColors.recycle();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment