如何动态生成TextView

时间:2014-08-16 04:21:43

标签: android android-layout

enter image description here我有一个应用程序,其中我想要一个布局,其中两个textview一对齐在左侧另一侧右侧。现在我正在得到textview,这是没有得到对齐,怎么做我不知道。请帮我搞定。

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

                    } 

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你试图将TextViews并排放置?

在这种情况下,您应该使用alignParent参数,试试这个:

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