我正在尝试在进度条中显示这两种方法的输出。但为了那个我需要做" long"两者的输出。这样做的正确方法是什么?
public class MainActivity extends Activity {
TextView ttvv1;
TextView ttvv2;
TextView ttvv3;
private ProgressBar pb3; // *
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ttvv1 = (TextView) findViewById(R.id.tv1);
ttvv1.setText(getTotalRAM());
ttvv2 = (TextView) findViewById(R.id.tv2);
freeMem();
pb3 = (ProgressBar) findViewById(R.id.progressBar1); // *
pb3.setMax((int) availableMegs); // *
pb3.setProgress(getTotalRAM); // *
}
private void freeMem() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
ttvv2.setText(availableMegs + " MB");
}
private String getTotalRAM() {
RandomAccessFile reader = null;
String load = null;
long total = 0;
try {
reader = new RandomAccessFile("/proc/meminfo", "r");
load = reader.readLine().replaceAll("\\D+", "");
total = Integer.parseInt(load) / 1024;
} catch (IOException ex) {
ex.printStackTrace();
}
return total + " MB";
}
}
这基本上是我的方法,但我收到错误 - getTotalRAM无法解析为变量而 availableMegs无法解析为变量
答案 0 :(得分:0)
public class MainActivity extends Activity {
TextView ttvv1;
TextView ttvv2;
TextView ttvv3;
private ProgressBar pb3; // *
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ttvv1 = (TextView) findViewById(R.id.tv1);
ttvv1.setText("" + getTotalRAM());
ttvv2 = (TextView) findViewById(R.id.tv2);
int availableMegs = freeMem();
pb3 = (ProgressBar) findViewById(R.id.progressBar1); // *
// pb3.setMax(availableMegs); // *
pb3.setProgress(getTotalRAM() * 100/availableMegs); // *
}
private void freeMem() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
ttvv2.setText(availableMegs + " MB");
return (int)availableMegs;
}
private int getTotalRAM() {
RandomAccessFile reader = null;
String load = null;
long total = 0;
try {
reader = new RandomAccessFile("/proc/meminfo", "r");
load = reader.readLine().replaceAll("\\D+", "");
total = Integer.parseInt(load) / 1024;
} catch (IOException ex) {
ex.printStackTrace();
}
return (int)total;
}
}
答案 1 :(得分:0)
您好像是在availableMegs
方法中声明并初始化freeMem
。因此,从该方法外部调用该变量将导致错误(方法不要继承在其他方法中声明的变量)。如果您计划在多个方法之间使用availableMegs
,您可以在onCreate
中声明/初始化它并将其传递给需要它的方法,或者您可以将其作为全局变量。
对于您的getTotalRam
字符串,看起来您在方法调用后缺少一对括号。将pb3.setProgress(getTotalRam);
更改为pb3.setProgress(getTotalRam());
。如您所指定的那样将其传递给setText
意味着应用程序将查找名为getTotalRam的变量,该变量当然不存在。
请记住,无论方法的返回类型是什么(在本例中为String),您总是需要通过包括括号来指定它是一个方法(而不是变量),即使没有参数被传递给它。
如果您需要将long
变量传递到进度条,那么您绝对不想将其转换为int
。你的专栏pb3.setMax((int) availableMegs);
似乎适得其反。一旦您在适当的位置(如上所述)宣布availableMegs
为long
,您就会希望将其保留为long
,因为&#39} ; s你的进度条需要什么。
希望这有帮助!