代码改变世界

Android通过图片名字获得ID

2012-07-25 22:41  javaspring  阅读(2489)  评论(0编辑  收藏  举报
package com.zhycheng;

import android.R.drawable;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import com.zhycheng.R;

public class TestClassActivity extends Activity implements OnClickListener {
	Button b;
	ImageView iv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button) findViewById(R.id.button1);
        iv=(ImageView) findViewById(R.id.imageView1);
        b.setOnClickListener(this);
    }
	@Override
	public void onClick(View v) {
		Class<com.zhycheng.R.drawable> cls = R.drawable.class;
	    try {
	        int value = cls.getDeclaredField("ic_launcher").getInt(null);
	        iv.setBackgroundResource(value);
	                    //Log.v("value",value.toString());
	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    } 
		
	}
}

这是整个Activity中的代码,其实关键也就那么几行。