LinearLayout с двумя текстовыми представлениями добавлен динамически с проблемой выравнивания - PullRequest
0 голосов
/ 23 июня 2011

У меня есть списки LinearLayouts с горизонтальной ориентацией, каждый из которых содержит два текстовых представления, добавленных динамически. Этот LinearLayout, наконец, обернут в мастер LinearLayout.

Я хочу, чтобы второе текстовое представление каждой линейной компоновки было выровнено вправо программно. Как я могу сделать это динамически.

Вот пример кода:

LinearLayout placeHolderLinearLayout =  (LinearLayout)findViewById(R.id.listhosts);

//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);

TextView h = new TextView(this);
h.setText("left");
h.setSingleLine(true);


TextView t = new TextView(this);
t.setText("right");
t.setSingleLine(true);

l.addview(h);
l.addview(t);

placeHolderLinearLayout.addView(l);

Имеется атрибут android: layout_alignParentRight. Но как установить это динамически в этом случае. Любая подсказка?

Ответы [ 3 ]

3 голосов
/ 23 июня 2011

android:layout_alignParentRight может быть применено к представлению только в том случае, если его родителем является RelativeLayout. Измените свой контейнер на него, и в 2 вложенных представлениях может использоваться любой из атрибутов layout_alignParent*.

Если вы не можете сделать это программно (что я не могу понять, как это сделать быстро), то вы всегда можете определить свой внутренний макет в XML (где вы можете легко получить правильный макет) и накачать вручную с помощью: 1006 *

LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View l = vi.inflate(R.layout.inner_relative_layout, null);

TextView leftTextView = (TextView) l.findViewById(R.id.left_text);
leftTextView.setText("left");
// ... fill in right text too

placeHolderLinearLayout.addView(l);

Редактировать: добавлено определение макета

Используйте макет, подобный этому, и надуйте его в коде, как указано выше:

<RelativeLayout android:id="@+id/inner_relative_layout" android:layout_width="fill_parent" android:layout_height="wrap_content">
    <TextView android:id="@+id/left_text" android_alignParentLeft="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <TextView android:id="@+id/right_text" android_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>

Вы будете создавать несколько таких макетов для каждого элемента, добавляемого в список.

1 голос
/ 30 ноября 2012

это просыпается и простой ответ ::

public class MainActivity extends Activity {

    TextView text[];
    TextView texto[];
    CheckBox check[];

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View view = findViewById(R.id.layout);
        text = new TextView[5];
        texto = new TextView[5];
        check = new CheckBox[5];

        for (int i = 0; i < 5; i++) {
            text[i] = new TextView(this);
            text[i].setText("First one is::" + i);
            texto[i] = new TextView(this);
            texto[i].setText("sennd one ibs::" + i);
            check[i] = new CheckBox(this);

            ((ViewGroup) view).addView(check[i]);
            ((ViewGroup) view).addView(text[i]);
            ((ViewGroup) view).addView(texto[i]);
        }

    }
}
0 голосов
/ 23 июня 2011

Пожалуйста, попробуйте ниже

LinearLayout placeHolderLinearLayout =  (LinearLayout)findViewById(R.id.listhosts);

//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);

TextView h = new TextView(this);
txt1.setGravity(Gravity.LEFT);
h.setText("left");
h.setSingleLine(true);


TextView t = new TextView(this);
txt1.setGravity(Gravity.RIGHT);
t.setText("right");
t.setSingleLine(true);

l.addview(h);
l.addview(t);

placeHolderLinearLayout.addView(l);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...