我正在尝试在函数中设置一个值(全局)并在android中的“On create()”函数外部访问它 我尝试将全局变量设为静态,甚至尝试将其写入“编辑文本”并在“on create()”中解析它。但它一直初始化为0.0(变量是double类型) 当我尝试在“on create()”中访问时,
哦,我无法返回该值,因为该函数太嵌套,因此所有层次结构都太复杂。 :(
谁能帮我解决这个问题;
public class TryActivity extends Activity
{
double BAT;\\ global value
public void onCreate(Bundle savedInstanceState)
{
disp(); // calling the function disp to set the value to BAT
String To_string=Double.toString(BAT);
System.out.println("Current Battery level ==="+To_string); \\ prints 0.0 the wrong value
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void disp(){
this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent){
double level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
BAT=level;
Textview1 = (EditText) findViewById(R.id.Textview1);
Textview1.setText(Double.toString(BAT)); // sets the correct value
System.out.println("bbbattererrerey 1 "+Double.toString(BAT)); //prints the correct value
}
};
}
最佳答案
只需在类中将变量全局初始化为
关于android - 访问函数外部的全局值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487815/