[英]Distinguishing which android button in an array of android buttons was clicked with buttons pointing to a single method
從這張圖片可以看出,我以鍵盤樣式設置了多個按鈕。 我在xmln中讓每個按鈕的onClick指向我的btnKeyPress方法。 我打算為此方法設置一個開關/大小寫,但想知道v.getId是否是區分按哪個按鈕的常規方法,並想知道是否有更好的方法。 我主要擔心的是v.getId是否會更改或根據我的日志保持不變,無論該應用程序在哪部手機上運行。
例如:這是我的Space和Backspace鍵的XML屬性
<Button
android:id="@+id/btnKeySpace"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="25"
android:onClick="btnKeyPress"
android:text="Space" />
<Button
android:id="@+id/btnKeyBackspace"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="75"
android:onClick="btnKeyPress"
android:text="Bkspc" />
這就是所謂的
public void btnKeyPress(View v){
System.out.println(v.getId());
}
v.getId()
將始終返回在布局xml中設置的android:id
。 所以,是的,使用它來識別按鈕不會有問題。
switch (v.getId()) {
case R.id.btnKeySpace:
break;
case R.id.btnKeyBackspace:
break;
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.