2017-02-25 92 views
0

我的Android應用程序不顯示任何值,即使它有它自己的權利ID。爲什麼它不起作用?由於不設置TextView

public class MainActivity extends AppCompatActivity { 
int[] marks = {1, 2, 4, 5}; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    for (int i = marks.length; i == 0; i--) { 
     int total = 0; 
     total = total + marks[i]; 
     float markAvereage = (float) total/marks.length; 
     setMarkText(i, markAvereage); 
    } 
} 
private void setMarkText(int i, float markAvereage) { 
    String textViewID = "mark" + i; 
    int resID = getResources().getIdentifier(textViewID, "id", getPackageName()); 
    TextView markTv = ((TextView) findViewById(resID)); 
    markTv.setText("Ø "+ (int) markAvereage); 
} 
} 

回答

0
public class MainActivity extends AppCompatActivity { 
    int[] marks = {1, 2, 4, 5}; 
    LinearLayout mLinearLayout; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    mLinearLayout = new LinearLayout(this); 
    setContentView(mLinearLayout); 
    mLinearLayout.setOrientation(LinearLayout.VERTICAL); 

    for (int i = 0; i <= marks.length; i++) { 
     float markAverage = (float) i/marks.length; 
     setMarkText(markAverage); 

    } 
} 

    private void setMarkText(float markAverage) { 
     TextView markTv = new TextView(this); 
     markTv.setText(String.valueOf(markAverage)); 
     mLinearLayout.addView(markTv); 
    } 
} 
+0

但即使是這種代碼粘貼到你不能因爲你必須把3個參數爲方法setMarkText,你放在那裏僅有2 –

+0

編輯,請嘗試上面的代碼。 –

+0

resID在循環外部聲明,因此無法在for循環內達到 –