2009年9月6日 星期日

動態Spinner來變更Image

所需功能
  1. 取得res/drawable資料夾下的所有檔案名稱
  2. 由檔案名稱取得ResourceID
  3. 點選並顯示圖檔
package java2.tw;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class mySpinner extends Activity {

private Spinner mySpinner;
private ImageView myImageView;
private ArrayAdapter myArrayAdapter;
static String[] myResource;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mySpinner = (Spinner) findViewById(R.id.mySpinner);
myImageView = (ImageView) findViewById(R.id.myImageView);
getResourceName();
myArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, myResource);
mySpinner.setAdapter(myArrayAdapter);

mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView arg0, View arg1,
int arg2, long arg3) {
myImageView.setImageResource(getResourceIDByName(
R.drawable.class, myResource[arg2]));

}

@Override
public void onNothingSelected(AdapterView arg0) {
}
});
}

private void getResourceName() {
String[] resource;
List list = new ArrayList();
for (Field f : R.drawable.class.getDeclaredFields()) {
try {
list.add(f.getName());
} catch (Exception e) {
Toast.makeText(this, "圖片目錄載入失敗", Toast.LENGTH_SHORT).show();
}
}
resource = new String[list.size()];
for (int i = 0; i <>
resource[i] = list.get(i);
}
myResource = resource;
}

private int getResourceIDByName(Class aClass, String resourceName) {
Field[] drawableFields = aClass.getFields();
int resourceID = 0;
for (Field f : drawableFields) {
if (resourceName.equals(f.getName())) {
try {
resourceID = f.getInt(null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return resourceID;
}
}

沒有留言: