2016-12-05 26 views
0

私はAndroidプログラミングには新しく、現在、単純なJavaの実装を理解しようとしています。 私がしようとしているのは、Androidスタジオに20個のtextViewを追加する方法を理解することです。つまり、ここで何が最善の選択です。 それはですか:Javaを使ってAndroidに20個のtextViewを追加する

a)手動で20個のtextViewを追加し、ボタンAをクリックすると、すべてのtextViewが数式で更新されます。私はこれが不要なJavaコードと繰り返しを作成すると信じています。

b)forループを作成し、textViewを1つ追加し、メソッドを使用して自動的に更新します。これまで私がしてきたこと。下のコード(IMMAGINE MainCalculate 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); 

    } 

おかげで、よろしく、

答えて

1

あなたは本当にあなたがこのようにそれを行うことができます20 TextViewsを追加したい場合は 関数計算( 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) {} 
    } 
} 

これは実際にそれが(良い)このためAsynchTaskを実装するお使いのデバイスのハードウェアに応じて少しかかる場合があり、20 TextViewsを追加します。 は、私は理解しましたあなたの質問は正しく?

+0

あなたは私の質問をしました。私はforループを使用するか、手動で20のtextViewを追加する必要があるかどうかを理解したかったのです。答えは "use loop"で、次にxml/javaでフォーマットします。ありがとう、 – zypa

+0

はい、そうです。最良のソリューションについては、下の私の例を参照してください。 –

1

ここでは、AsynchTaskを使用した方が良い方法です。これはあなたのアプリがフリーズするのを防ぎます。ここで

calculation myCalc = new calculation(this); 
myCalc.execute(); 

はAsyncTaskクラスは、ループを通じてテキストビューを作成します

<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> 
0

内部LineraLayoutでScrollViewを使っ

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) {} 
    } 
} 

最適なソリューションです。その良いアプローチ。

関連する問題