我是Android编程的新手,目前试图了解其中的简单Java。我要做的是了解如何在Android Studio中添加20个文本视图。我的意思是,这里的最佳选择是什么。是:
a)手动添加20个文本视图,当我单击按钮时,所有文本视图将使用公式进行更新。我相信这将创建不必要的Java代码和重复。
b)创建一个for循环,添加一个文本视图,然后通过方法自动更新。到目前为止,我所做的。下面的代码(不绝版,有一个按钮连接到主计算ID:
double realPrice = 10;
double total = (realPrice * 2)+1;
double increase = 0.1;
TextView percentageTextView = (TextView) findViewById(R.id.percentageTextViewID);
public void MainCalculate (View view) {
MarketValueAnswer.setText(Double.toString(marketValueAnswer));
for (double i=realPrice; i<=total; i+=increase) {
double formula = ((realPrice*increase) + realPrice);
increase+=0.05;
percentageTextView.append("n" + formula);
}
谢谢,最好的问候,
如果您真的想添加20个文本视图,则可以这样做。单击butten时调用函数计算()。
double realPrice = 10;
double total = (realPrice * 2)+1;
double increase = 0.1;
private void calculation() {
for (double i=realPrice; i<=total; i+=increase) {
double formula = ((realPrice*increase) + realPrice);
increase+=0.05;
try {
TextView txtView = new TextView(this);
txtView.setText(Double.toString(formula));
ll.addView(txtView);
} catch (Exception ignored) {}
}
}
这确实会添加20个文本视图,这可能需要一些根据您的设备硬件(更好地实现AsynchTask)。我是否正确理解了您的问题?
这是使用asynchtask的更好方法。这将阻止您的应用程序冻结。
calculation myCalc = new calculation(this);
myCalc.execute();
这是Asynctask类
private class calculation extends AsyncTask<Void, Double, Void> {
//we need this context for the TextView instantiation
private Context mContext;
private calculation(Context context){
mContext = context;
}
@Override
protected Void doInBackground(Void... voids) {
for (double i=realPrice; i<=total; i+=increase) {
double formula = ((realPrice*increase) + realPrice);
increase+=0.05;
publishProgress(formula);
}
return null;
}
protected void onProgressUpdate(Double... s) {
try {
TextView txtView = new TextView(mContext);
txtView.setText(Double.toString(s[0]));
ll.addView(txtView);
} catch (Exception ignored) {}
}
}
最佳解决方案使用scrollview,内部的衬里
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
通过循环创建文本视图。这是一个更好的方法。