2013-05-17 12 views
5

Hej, jestem nowy w programowaniu Android i mam mały problem Chcę utworzyć listView z ImageView i TextView. Ten kod działa, ale faktycznie chciałem użyć tablic które utworzone przed tak:Android za pomocą zasobów tablicy xml

int[] img = getResources().getIntArray(R.Array.img); 
package com.simplelistviewwithlistactivity; 

import android.app.AlertDialog; 
import android.app.AlertDialog.Builder; 
import android.app.ListActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.widget.ListView; 

public class ListActivityS extends ListActivity { 
    int[] img = { R.drawable.r1, R.drawable.r2, R.drawable.skycubemap1, 
      R.drawable.skycubemap1, R.drawable.skycubemap2, 
      R.drawable.skycubemap3, R.drawable.skycubemap4, 
      R.drawable.skycubemap5 }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     getListView().setDividerHeight(2); 
     getListView().setAdapter(new BindDataAdapter(this, img, item)); 
    } 

    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) { 
     super.onListItemClick(l, v, position, id); 
     Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage(item[position] + " is clicked."); 
     builder.setPositiveButton("OK", null); 
     builder.show(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_list, menu); 
     return true; 
    } 

    private String item[] = { "This is list Item1", "This is list Item2", 
      "This is list Item3", "This is list Item4", "This is list Item5", 
      "This is list Item6", "This is list Item8", "This is list Item8" 
+0

Można użyć kolorów w tablicy, wykonując następujący przykład: http://stackoverflow.com/a/17584066/560600 –

Odpowiedz

20

Załóż XML jak poniżej i umieścić go w RES/wartości/arrays.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <array name="icons"> 
     <item>@drawable/home</item> 
     <item>@drawable/settings</item> 
     <item>@drawable/logout</item> 
    </array> 
    <array name="colors"> 
     <item>#FFFF0000</item> 
     <item>#FF00FF00</item> 
     <item>#FF0000FF</item> 
    </array> 
</resources> 

Następnie użyj kodu:

Resources res = getResources(); 
TypedArray icons = res.obtainTypedArray(R.array.icons); 
Drawable drawable = icons.getDrawable(0); 

TypedArray colors = res.obtainTypedArray(R.array.colors); 
int color = colors.getColor(0,0); 

Źródło: http://developer.android.com/guide/topics/resources/more-resources.html

Powiązane problemy