向下滾動我的答案。這個問題並不重要,代碼只是令人困惑。如何一次添加多個按鈕監聽器?
是否有一個函數可以讓我獲取id標籤,以便我可以輕鬆地循環按鈕偵聽器?目前,我有我的主「容器」的xml,裏面片段這行代碼:
public static final Map<String, Integer> RMAP = createMapR();
// Map of widget id's in R
private static Map<String, Integer> createMapR() {
Map<String, Integer> result = new HashMap<String, Integer>();
for (Field f : R.id.class.getDeclaredFields()) {
String key = f.getName();
Integer value = 0;
try {
value = f.getInt(f);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
result.put(key, value);
}
return Collections.unmodifiableMap(result);
}
,然後我的碎片將拿起RMAP和交叉與我指定的標籤之一。我這樣做是因爲我有幾個按鈕,並且指定了一大堆聽衆似乎效率低下,然後我就偏離了這個代碼。
public class BottomFragment extends Fragment {
private final String[] LABELS = {"button_do_1", "button_woah_2", "button_foo_1",
"button_hi_2"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bottom_fragment, container, false);
for (String item : LABELS) {
if (Container.RMAP.containsKey(item)) {
((Button) v.findViewById(Container.RMAP.get(item)))
.setOnClickListener(this);
}
}
return v;
}
然而,如果有一種方法,通過機器人的列表進行迭代:ID項目專門BottomFragment()我也不會,甚至需要的一個代碼塊,它會消除ID的的手動列表我已經輸入了。
上面的代碼工作。但是,如果我能夠獲得該特定片段的ID列表,我可以在一個很好的循環中添加onClick監聽器,而不是超過15行setOnCLickListener(this)。現在我正在使用兩個列表。一個自動填充,其中包含每個R.id()變量。在我的情況下,它大多是按鈕和其他一些小部件。 – Steven
如果該類型的函數不存在或者可以用來獲取該視圖的窗口小部件ID的函數的組合,那麼很好,上面的代碼工作,它只是不是自動的,因爲我有LABELS鍵入ID的手動。 – Steven
你應該使用SparseArray來實現這種功能:https://developer.android.com/reference/android/util/SparseArray.html – hwrdprkns