Jupiter
Jupiter

Reputation: 665

Programmatically set constraints to textViews created at run-time?

The code below creates a varying amount of textViews at run-time depending on the number of keys in friendMap:

        generatedViews = new TextView[numberOfFriends];
        int count = 0;
        for (String k : friendMap.keySet()) {


            TextView textView = new TextView(this);
            textView.setVisibility(View.VISIBLE);
            textView.setText(k);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f);
            textView.setGravity(Gravity.CENTER);


            String mutual = friendMap.get(k);

            if (mutual.equals("no")) {
                textView.setBackgroundColor(Color.RED);
            } else {
                textView.setBackgroundColor(Color.GREEN);
            }
            linLayout.addView(textView);
            generatedViews[count] = textView;
            count++;
        }

My question is: how can I set constraints to the created textViews so they don't bunch?

Upvotes: 0

Views: 221

Answers (2)

TheLibrarian
TheLibrarian

Reputation: 1898

As @TheWandered said you should probably use RecyclerView.

But if for some reason it's not an option, here is how you can do it:

First thing, you are going to have to generate ID for each TextView, so you can target the constraints and then:

ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.connect(text_view_id,ConstraintSet.TOP, previous_text_view_id,ConstraintSet.BOTTOM,0);
// is equal to "layout_constraintTop_toBottomOf="previous_text_view_id"
constraintSet.applyTo(constraintLayout);

Upvotes: 0

Jupiter
Jupiter

Reputation: 665

It's simple:

Set the layout parameters of the LinearLayout with:

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(100, 20, 100, 20);
            linLayout.addView(textView, layoutParams);

Upvotes: 0

Related Questions