user3683036
user3683036

Reputation: 135

How to generate TextView dynamically

enter image description herei have an app in which i want a layout in which two textview one align on left side other on right side.right now i am getting textview which is not getting align,how to do that i dont know.please help me to get it.

 LinearLayout relativeLayout = null;

        relativeLayout = new LinearLayout(getContext());
                    relativeLayout.setOrientation(LinearLayout.HORIZONTAL);

                    RelativeLayout.LayoutParams relativeLayoutParams;

                    final TextView[] textView = new TextView[3];

                    // 1st TextView
                    textView[0] = new TextView(getContext());
                    textView[1] = new TextView(getContext());
                    relativeLayoutParams = new RelativeLayout.LayoutParams(width,
                            LayoutParams.WRAP_CONTENT);
                    textView[0].setPadding(10, 10, 5, 5);
                    textView[0].setText("");
                    textView[0].setId(1); // changed id from 0 to 1
                    textView[0].setText(object.getCCInfoLeft());

                    textView[0].setGravity(Gravity.LEFT);

                    if (textView[0] != null
                            && !textView[0].getText().equals("null")) {

                        relativeLayout.addView(textView[0], relativeLayoutParams);


                        textView[1].setText("");
                        textView[1].setTextAlignment(Gravity.RIGHT);

                        textView[1].setText(object.getCCInfoRight());
                        textView[1].setGravity(Gravity.RIGHT);

                        textView[1].setPadding(100, 10, 5, 5);

                        LinearLayout.LayoutParams rightGravityParams = new LinearLayout.LayoutParams(
                                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        rightGravityParams.gravity = Gravity.RIGHT;
                        relativeLayout.addView(textView[1], rightGravityParams);

                    } 

Upvotes: 0

Views: 150

Answers (1)

Reuven Chacha
Reuven Chacha

Reputation: 889

If I understand right, you are trying to put the TextViews side by side?

In this case, you should use alignParent parameter, try this:

RelativeLayout.LayoutParams TVparams = (RelativeLayout.LayoutParams)yourRightTextView.getLayoutParams();
TVparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//add next line just if you want it in the same line of the left one
TVparams.addRule(RelativeLayout.RIGHT_OF, R.id.yourLefttextView); 

yourRightTextView.setLayoutParams(params);

Upvotes: 2

Related Questions