zoukankan      html  css  js  c++  java
  • 通过资源名称得到资源id


    demo地址


    主要应用类

    package com.example.activitylibrary;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class LibraryActivity extends Activity {
    	String msg = "我是来自Jar中的Activity";
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(MResource.getIdByName(getApplication(), "layout", "activity_main"));
    		
    		TextView mTextView = (TextView) findViewById(MResource.getIdByName(getApplication(), "id", "textView1"));
    		mTextView.setText(msg);
    		
    		Button mButton = (Button) findViewById(MResource.getIdByName(getApplication(), "id", "button1"));
    		
    		mButton.setText(msg);
    		mButton.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				Toast.makeText(getApplication(), msg, Toast.LENGTH_SHORT).show();
    			}
    		});
    	}
    
    
    }
    
    具体工具类

    package com.example.activitylibrary;
    
    import android.content.Context;
    
    /**
     * 根据资源的名字获取其ID值
     * @author
     *
     */
    public class MResource {
    	public static int getIdByName(Context context, String className, String name) {
    		String packageName = context.getPackageName();
    		Class r = null;
    		int id = 0;
    		try {
    			r = Class.forName(packageName + ".R");
    
    			Class[] classes = r.getClasses();
    			Class desireClass = null;
    
    			for (int i = 0; i < classes.length; ++i) {
    				if (classes[i].getName().split("\$")[1].equals(className)) {
    					desireClass = classes[i];
    					break;
    				}
    			}
    
    			if (desireClass != null)
    				id = desireClass.getField(name).getInt(desireClass);
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (NoSuchFieldException e) {
    			e.printStackTrace();
    		}
    
    		return id;
    	}
    }
    







  • 相关阅读:
    STM32使用定时器实现输入捕获
    Leetcode#101 Symmetric Tree
    Leetcode#100 Same Tree
    Leetcode#26 Remove Duplicates from Sorted Array
    Leetcode#27 Remove Element
    Leetcode#83 Remove Duplicates from Sorted List
    Leetcode#70 Climbing Stairs
    Leetcode#66 Plus One
    Leetcode#36 Valid Sudoku
    Leetcode#67 Add Binary
  • 原文地址:https://www.cnblogs.com/flyingsir/p/3983699.html
Copyright © 2011-2022 走看看