在我深入研究之前,我對Android非常陌生,上個月剛剛開始學習Java。我試圖開發我的第一個簡單的應用程序時遇到了顛簸。在線隨機教程讓大多數障礙都跳了起來。我的代碼非常精彩。任何提示都表示讚賞。如何更改不同類別的變量?
上面的問題相當廣泛,但這是我想要做的:它基本上是一個血液酒精含量計算器/飲料守護者跟蹤器。基本佈局:http://i.imgur.com/JGuh7.jpg
沿着底部的按鈕都只是普通的鈕釦,不ImageButtons(曾與該問題),這裏有一個的一些示例代碼:
<Button android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_marginRight="5dp"
android:background="@drawable/addbeer"/>
的按鈕和TextView的都是main.xml中。
我有一個名爲Global.java類中定義的變量:
package com.dantoth.drinkingbuddy;
進口android.app.Activity;
公共類全球擴展活動{
public static double StandardDrinks = 0;
public static double BeerOunces = 12;
public static double BeerPercentAlcohol = .05;
public static double BeerDrink = BeerOunces * BeerPercentAlcohol;
public static double BeerDrinkFinal = BeerDrink * 1.6666666;
public static double ShotOunces = 1.5;
public static double ShotPercentAlcohol = .4;
public static double ShotDrink = ShotOunces * ShotPercentAlcohol;
public static double ShotDrinkFinal = ShotDrink * 1.6666666;
public static double WineOunces = 5;
public static double WinePercentAlcohol = .12;
public static double WineDrink = WineOunces * WinePercentAlcohol;
public static double WineDrinkFinal = WineDrink * 1.6666666;
public static double OtherOunces;
public static double OtherPercentAlcohol;
public static double OtherDrink = OtherOunces * (OtherPercentAlcohol * .01);
public static double OtherDrinkFinal = OtherDrink * 1.6666666;
public static double GenderConstant = 7.5; //9 for female
public static double Weight = 180;
public static double TimeDrinking = 60;
public static double Hours = TimeDrinking/60;
public static double Bac = ((StandardDrinks/2) * (GenderConstant/Weight)) - (0.017 * Hours);
}
最後一個變量是重要的組成部分。它根據涉及的因素計算您的BAC。
當我按下添加啤酒按鈕(Button01)時,我將它添加到StandardDrinks,模擬喝一杯啤酒。 Bac公式中的其他變量在Global.java中分配給它們的值。
,使啤酒的按鈕做的東西是我的正常類的代碼,drinkingbuddy.java:
public class DrinkingBuddy extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Global.StandardDrinks = Global.StandardDrinks + Global.BeerDrinkFinal;
Toast.makeText(DrinkingBuddy.this, "Mmmm... Beer", Toast.LENGTH_SHORT).show();
}
});
通過我的感覺,StandardDrinks現在應該有1的值。然而,當我點擊計算BAC按鈕(Button05)它只輸出變量Bac,就好像StandardDrinks仍然設置爲0.下面是Calculate BAC按鈕(Button05)的代碼:
Button button4 =(Button)findViewById(R.id.Button05 ); button4.setOnClickListener(新OnClickListener(){@Override 公共 無效的onClick(視圖v){
TextView texty;
texty = (TextView) findViewById(R.id.texty1);
texty.setText("Your BAC is " + Global.Bac);
}
});
它輸出下面的文本視圖: 「你BAC爲-0.017」 這是北如果StandardDrinks的值仍然爲0,那麼很明顯,這些類之間存在一些問題。任何人都可以幫助我嗎?
公式的其他元素(重量,花費的時間以及酒精%等等)是變量,因爲我最終會允許用戶在設置中更改這些值。
我聽說過水冷卻器,全局變量不是很好的編程風格,但這是我最接近實現它的工作。任何其他的做法都非常受歡迎!
點1錯了。我想你的意思是說,定義爲「最終」的變量不能改變。聲明'靜態'意味着類有一個變量,而不是實例。 點2是正確的。 – 2010-06-06 03:28:21