2014-11-04 72 views
0

因此,我正在迭代Strings和Booleans的HashMap。我爲每個String在LinearLayout上放置一個TextView。這很好。我需要做的是將布爾值的TextView放置到每個String TextView的右邊。有任何想法嗎?這就是我要尋找...以編程方式在LinearLayout中並排設置兩個TextView

enter image description here

LinearLayout planLayout = (LinearLayout) findViewById(R.id.planLayout); 
for (Map.Entry<String, Boolean> entry : plans.entrySet()) { 
    String key = entry.getKey(); 
    Boolean value = entry.getValue(); 
    TextView keyTV = new TextView(this); 
    keyTV.setText(key + " | "); 
    // here is where I want to set a TextView of the Boolean to the right of the keyTV 
    planLayout.addView(keyTV); 
} 

使用ClickableSpan

LinearLayout planLayout = (LinearLayout) findViewById(R.id.planLayout); 

    for (Map.Entry<String, Boolean> entry : plans.entrySet()) { 
     String key = entry.getKey(); 
     Boolean value = entry.getValue(); 
     TextView keyTV = new TextView(this); 
     SpannableString ss = new SpannableString(value.toString()); 
     ClickableSpan clickableSpan = new ClickableSpan() { 
      @Override 
      public void onClick(View textView) { 
       Toast.makeText(getApplicationContext(), "clicked", 
          Toast.LENGTH_SHORT).show(); 
       System.out.println("Hello"); 
      } 
     }; 
     ss.setSpan(clickableSpan, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
     keyTV.setText(key + " | " + ss); 
     keyTV.setMovementMethod(LinkMovementMethod.getInstance()); 
     keyTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20); 
     planLayout.addView(keyTV); 
    } 
} 

回答

1

一個LinearLayout只能在一個方向鋪設更新時間:垂直,在這種情況下。來自docs

將其子項排列在單列或單排 行的佈局。行的方向可以通過調用setOrientation()來設置。

雖然您可以嵌套另一個水平LinearLayout(每個項目),並添加TextViews作爲其子,在這種情況下,它似乎要簡單得多,只是串聯值到同一個TextView的對象。

如果您只需要部分文本是可點擊的,則可以使用ClickableSpan來實現此目的(請記住也要使用setMovementMethod()以使其工作)。

+0

我已經這樣做了,但右側(布爾值)最終將是可點擊的,其中左側不會是。因此,我需要將它們分開 – Harry 2014-11-04 20:34:19

+0

感謝ClickableSpan上的提示。將檢查出來。 – Harry 2014-11-04 20:36:58

+0

@你可以使用spanned字符串來僅使textview的一部分可點擊。或者,也可以嵌套佈局。 – matiash 2014-11-04 20:37:00

相關問題