Search code examples
androidandroid-layoutandroid-relativelayout

Pervent overlapping of Two paired TextView in a row with multiline TextView in RelativeLayout programmatically?


I manage to achieve this by adding to_end_of of a relative layout, but long texts also seems to have problem enter image description here

here's the code for doing that:

        RelativeLayout.LayoutParams keyParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        keyParams.addRule(RelativeLayout.ALIGN_PARENT_END);

        RelativeLayout.LayoutParams valueParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        valueParams.addRule(RelativeLayout.ALIGN_PARENT_START);



        for (Map.Entry<String, String> item : model.getCompanyProperties().entrySet()) {
            RelativeLayout layout = new RelativeLayout(this);
            TextView keyText = new TextView(this);
            keyText.setLayoutParams(keyParams);
            keyText.setText(item.getKey());
            keyText.setSingleLine(false);


            TextView valueText = new TextView(this);
            valueText.setGravity(Gravity.START);
            valueText.setTextSize(18);
            valueText.setText(item.getValue());
            valueParams.addRule(RelativeLayout.START_OF, keyText.getId());
            keyParams.addRule(RelativeLayout.END_OF, valueText.getId());
            valueText.setLayoutParams(valueParams);


            layout.addView(keyText);
            layout.addView(valueText);
            repoPropertiesLayout.addView(layout,
                    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        }

    }

Solution

  • Finally I managed to overcome the situation with setting weight to both view and creating LinearLayout instead, here's the code:

     LinearLayout layout = new LinearLayout(this);
     layout.setOrientation(LinearLayout.HORIZONTAL);
     layout.setGravity(Gravity.END);
     TextView valueText = new TextView(this);
     valueText.setText(item.getValue());
     layout.addView(valueText);
     TextView keyText = new TextView(this);
     keyText.setText(item.getKey());
     LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                    0,
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    1.0f
            );
     valueText.setLayoutParams(param);
     keyText.setLayoutParams(param);
     layout.addView(keyText);