在我深入研究之前,我对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