2014-11-04 121 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

相关问题