Harry
Harry

Reputation: 782

Programmatically setting two TextView side-by-side in LinearLayout

So, I am iterating through a HashMap of Strings and Booleans. I am placing a TextView on the LinearLayout for each String. This is all good. What I need to do is place a TextView of the Boolean value to the right of each String TextView. Any ideas? This is what I am looking for...

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

Updated using 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);
    }
}

Upvotes: 0

Views: 678

Answers (1)

matiash
matiash

Reputation: 55360

A LinearLayout can only be laid in one direction: vertically, in this case. From the docs:

A Layout that arranges its children in a single column or a single row. The direction of the row can be set by calling setOrientation().

While you could nest another horizontal LinearLayout (one for each item) and add the TextViews as its children, in this case it would seem to be much simpler to just concatenate the value into the same TextView object.

If you need only part of the text to be clickable, you can use ClickableSpan to achieve this (remember to use setMovementMethod() too, for it to work).

Upvotes: 1

Related Questions