2012-03-18 88 views
0

我有一個空的LinearLayout,我需要給它添加一個動態數字TextView。然而,當我使用下面的代碼中,只有第一TextView所示:以編程方式添加TextViews

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

    String[] listofnumbers = new String[1000]; 
    for (int i = 0 ; i < 1000 ; ++i) { 
     listofnumbers[i] = "null"; 
    } 

    Context context = getBaseContext(); 

    String text = null; 

    Uri uri = Uri.parse("content://sms"); 
    Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); 

    String[] columnNames = cursor.getColumnNames(); 
    LinearLayout lv = new LinearLayout(context); 
    LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dip(48)); 

    boolean v = true; 
    while (cursor.moveToNext()) 
    { 
     String numberString = (cursor.getString(cursor.getColumnIndexOrThrow("address"))).replace(" ", ""); 

     int i = 0; 
     boolean numberNotPresent = true; 
     for ( ; listofnumbers[i] != "null" ; ++i) { 
      if (numberString.equals(listofnumbers[i]) ) { 
       numberNotPresent = false; 
      } 
     } 
     if (numberNotPresent == true) { 
      text = (CharSequence) "From: " + cursor.getString(cursor.getColumnIndexOrThrow("address")) + ": " + cursor.getString(cursor.getColumnIndexOrThrow("body")); 
      listofnumbers[i] = numberString; 
      TextView tv = new TextView(this); 
      tv.setText(text); 
      tv.setLayoutParams(textViewParams); 
      lv.addView(tv); 
     } 
    } 
    setContentView(lv); 
} 

我在哪裏出了錯?

+0

你確定'if(numberNotPresent == true)'符合條件嗎?可能會添加一些日誌記錄,看看你是否真的進入該代碼並嘗試添加另一個TextView – dldnh 2012-03-18 16:28:51

+0

刪除一次條件並再次檢查,如果這次得到TextView,意味着您的狀況有問題。我也會和@dldnh一起去記錄日誌。 – noob 2012-03-18 16:45:52

+0

設置thr線性佈局的參數 – 2012-03-18 16:50:38

回答

3

試圖改變這兩條線:

LinearLayout lv = new LinearLayout(context); 
    LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, dip(48)); 

這些:

LinearLayout lv = new LinearLayout(context); 
     lv.setOrientation(LinearLayout.VERTICAL); 
     LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

基本上你需要爲LV的LinearLayout方向設置爲垂直爲默認的一個是水平的。

1

我不確定,但可能是爲每個textView設置了fill_parent參數?第一個textView顯示在您的所有佈局上。