[英]How can i pass the class object into the BroadCastReviever from the mainActivity class
[英]Can I pass a parameter from a layout XML to a method in the MainActivity?
如果這是一個菜鳥問題,對不起,但是我是XML和Android整體的新手。
我正在用Android做一個基本的計算器,基本上我想寫一個方法來處理所有的數字按鈕按下。 我想像這樣將參數從XML傳遞到方法中。
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/button_8"
android:textSize="40dp"
android:onClick="num_pressed(8)"
/>
並在主要活動中使用該方法對該數字進行任何處理(我尚未確定與該數字究竟要做什么,但這不是我的問題的一部分)。
為了澄清,在我的應用程序中,我有用於數字0-9,符號“ +”,“-”,“ *”,“ /”,“”的按鈕。 和“ C”。 我認為不必為每個數字編寫單獨的方法,而是讓所有數字使用相同的方法,然后簡單地傳入一個變量,以便對它們全部以相同的方式工作會更有效。
我可以這樣做還是必須完全不同地去做?
不,您不能將參數傳遞給方法,但可以為視圖設置標簽並在代碼中檢查它。 實現此目的的簡單方法是為Button設置標簽:
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/button_8"
android:textSize="40dp"
android:onClick="num_pressed"
android:tag="8"
/>
在您的代碼中,您可以這樣做:
public void num_pressed(View view) {
String a = (String) view.getTag(); // here will be 8 for button.
}
您不能通過XML傳遞參數,但是可以這樣做,
您在strings.xml中:8
您在layout.xml中:
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/button_8"
android:textSize="40dp"
android:onClick="num_pressed"
/>
在活動中對數字執行此操作:
public void num_pressed(View view) {
int number = Integer.parseInt(((Button) view).getText().toString());
}
編輯:同樣,對於符號,只需跳過解析為Integer的操作,我建議使用兩種不同的方法來處理數字和符號,因為(如您所說)在Calculator中,這些鍵的工作方式將有很大不同。
請按照以下代碼獲取按鈕事件。
public void num_pressed(View view) {
switch (view.getId()) {
case R.id.button1:
//perform operation
break;
case R.id.button2:
//perform operation
break;
case R.id.button3:
//perform operation
break;
case R.id.button4:
//perform operation
break;
case R.id.button5:
//perform operation
break;
case R.id.button6:
//perform operation
break;
case R.id.button7:
//perform operation
break;
case R.id.button8:
//perform operation
break;
case R.id.button9:
//perform operation
break;
case R.id.buttonplus:
//perform operation
break;
default:
break;
}
}
單擊按鈕時,可以調用方法。 另外,您可以將標簽分配給xml中的視圖(在您的情況下為按鈕)。 (標簽基本上是視圖記憶的一種方式。)
為了清楚android:onClick="MethodName"
,請使用android:onClick="MethodName"
設置要調用的方法。 並使用android:tag="tagValue"
將標簽分配給每個視圖。 可以使用view.getTag()
從方法中檢索標簽。
示例代碼:
xml:
<Button
...Other Parameters...
android:id="@+id/Button2"
android:tag="2"
android:onClick="method1"/>
<Button
...Other Parameters...
android:id="@+id/Button3"
android:tag="3"
android:onClick="method1"/>
Java:
public void method1(View v){
String tagValue = (String) v.getTag();
if(tagValue.equals("2")){
// add relevant code here
}
else if(tagValue.equals("3")){
// add relevant code here
}
//complete the ramaining code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.