我目前正在學習 Android 開發,并且對在 MainActivity.java 檔案中添加某些功能的位置感到困惑。
一些背景:我正在使用 Java 在 Android 中設計一個基本的咖啡應用程式。我在 XML 檔案中添加了一個用于澆頭的復選框。
<CheckBox
android:id="@ id/checkbox_whipped_cream"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="Whipped Cream"
android:paddingLeft="20dp"
android:textSize="25dp" />
當我點擊我的應用程式上的訂單按鈕時??,我應該能夠看到這個 Whipped Cream 復選框被勾選并顯示在訂單摘要中。
那么,通常應該在 .java 檔案中的何處添加功能?
這是我到目前為止撰寫的java代碼:
package android.example.updated_coffee_app;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
int quantity = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void increment(View view) {
quantity = quantity 1;
display(quantity);
}
public void decrement(View view) {
quantity = quantity - 1;
display(quantity);
}
public void order(View view) {
CheckBox whippedCream = (CheckBox) findViewById(R.id.checkbox_whipped_cream);
int price = calculatePrice();
String priceMessage = createOrderSummary(price);
displayMessage(createOrderSummary(price));
}
private String createOrderSummary(int price) {
String priceMessage = "Name : Toshali ";
priceMessage = priceMessage "\nCoffee Quantity: " quantity;
priceMessage = priceMessage "\nTotal: $" price;
priceMessage = priceMessage "\nThank You!";
return priceMessage;
}
private int calculatePrice() {
int price = 5 * quantity;
return price;
}
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
private void display(int numbers) {
TextView quantityTextView = (TextView) findViewById(R.id.quantityOfCoffee);
quantityTextView.setText(" " numbers);
}
}
一般來說,我很困惑在哪里添加一段特定的代碼?在什么方法(功能)?或者我們是否為所有組件創建單獨的方法?
在影像中,我應該能夠看到“鮮奶油?: True' 在訂單摘要中。
生奶油復選框選項
uj5u.com熱心網友回復:
現在你只在order運行時檢查你的復選框的狀態。如果您想立即對選中/未選中的復選框做出反應,則需要指定一個偵聽器。
復選框允許您在 XML 中指定一個方法,只要其狀態更改為“ android:onClick=”,就會呼叫該方法。
您可以像這樣更改代碼:
在您的 xml 布局中,將其添加到您的CheckBox元素中:
android:onClick="onCheckboxClicked"
在您的活動中,添加此新方法:
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
if(checked) {
// TODO: Show that whipped cream is selected
}
else {
// TODO: Show that whipped cream is not selected
}
}
參考:https ://developer.android.com/guide/topics/ui/controls/checkbox#java
對 Android 應用代碼結構的看法
您應該有單獨的方法來回應 UI 事件,例如單擊按鈕和切換復選框。理想情況下,這些方法應該更新 UI 狀態物件。
Google 自以為是的建議是,您的 UI 狀態應由 UI 狀態資料類確定。在您的示例中,一個 UI 狀態類將保存價格、數量和所選附加品(生奶油)的資料。
然后像按鈕按下這樣的事件將更新 UI 狀態物件。每當您的 UI 狀態發生變化時,您都會更新 UI。
在此處查看本指南:https ://developer.android.com/jetpack/guide/ui-layer#define-ui-state
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436592.html
