2013-07-17 26 views
-4

我想通過使用存儲在變量中的名稱來使用java中的對象。例如:通過在字符串中使用名稱來引用對象android

String[] str={"name1","name2"}; 
Button name1 = (Button) findViewById(R.id.but1); 
Button name2 = (Button) findViewById(R.id.but2); 

//what i want to do is : instead of 
name1.setText("TEXT"); 

//to use something like 
Button.str[0].setText("TEXT"); 
+0

爲什麼不只是有一個按鈕的數組或對象,如果它必須是多種類型。或者你可以使用某種散列表或字典 –

回答

2

爲什麼不使用Map?

Map<String,Button> buttons = new HashMap<String,Button>(); 
buttons.put("buttonA", new Button()); 
buttons.get("buttonA"); // gets the button... 
0

要做到這一點,最聰明的方法是使用鍵值數據結構來查看按鈕。

我總是使用HashMap,因爲它是O(1)查找時間。

繼承人一個簡單的例子:

HashMap<String, Button> map = new HashMap<String, Button>(); 

Button name1 = (Button) findViewById(R.id.but1); 
map.put("name1", name1); 

Button name2 = (Button) findViewById(R.id.but2); 
map.put("name2", name2); 

map.get("name1"); //Will return button name1 
0

使用HashMap<String, Button>。這提供了O(1)中的查找,並允許將字符串作爲關鍵字。

首先,創建一個HashMap:

HashMap<String, Button> buttons=new HashMap<>(); //The <> works in JDK 1.7. Otherwise use new HashMap<String, Button>(); 

然後添加按鈕:

buttons.put("name1", findViewById(R.id.but1)); 
buttons.put("name2", findViewById(R.id.but2)); 

,並讓他們:

Button btn=buttons.get("name2"); 

可以調整get(用於字符串選擇按鈕。

相關問題