Подтвердить что ты не робот

Как разделить линейную компоновку на два столбца?

Мне нужно разделить однолинейную компоновку на две колонки (Как столбцы газеты). Линейный макет содержит текстовый вид и образ-просмотр

Я взял ширину экрана и разделил ее на половину и сделал TextView и ImageView для входа в первый столбец, т.е. A B C блоков на рисунке ниже. Теперь оставшиеся TextView и 'ImageView должен перейти в следующий столбец, например, в D E F, как это происходит. Поэтому было бы полезно, если бы кто-нибудь дал мне какой-либо код или идеи для его реализации. Я пробовал с GridView, который не подходит для моей проблемы. Поскольку размеры TextView и ImageView не определены.

enter image description here

Я не знаю, как разделить макет Liner. Я попытался рассчитать высоту rootlayout как это

linearLayout.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int linsize=linearLayout.getHeight();
                int relsize=root.getHeight();
                int textsize=txt1.getHeight();
                mainheight=relsize;
                subheight=linsize;
                Toast.makeText(getApplicationContext(), "Linerlayout "+linsize, Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "Relative layout"+relsize, Toast.LENGTH_LONG).show();
                Toast.makeText(getApplicationContext(), "text height "+textsize, Toast.LENGTH_LONG).show();

                if(mainheight==subheight)
                {
                    Toast.makeText(getApplicationContext(), "make a new linear layout", Toast.LENGTH_LONG).show();
                    createsubview();
                }
            }
        }); 

Снимок экрана

enter image description here

4b9b3361

Ответ 1

Вы можете легко сделать это с помощью вложенных LinearLayouts:

 <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/item" />

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >

            <ImageView
                content here/>

            <TextView
                content here/>

        </LinearLayout>
    </LinearLayout>

Тогда все, что вам нужно сделать, это положить A, B и C в первую вертикальную компоновку, а D, E и F - во второй.

Ответ 2

Вы не можете сделать это с помощью GridView. Для этого вам нужно создать пользовательский вид.

если вы знаете, насколько велики ваши элементы сетки, вы можете разрезать некоторые углы. GridView сложнее в основном потому, что он имеет дело с элементами любого размера и загружает их динамически. Для вас может быть проще:

1.Создайте горизонтальныйScrollView с горизонтальным LinearLayout внутри.

2. Определите, сколько строк вашего элемента поместится на экране. Вызовите эти строки.

3. Пока у вас все еще есть элементы, которые вам нужны для компоновки:

    1.Create a vertical LinearLayout, adding rows or less items to it.
    2.Add your new vertical LinearLayout to the horizontal one.

Есть некоторые недостатки по сравнению с тем, что вам поможет "горизонтальный GridView":

1.All the views are loaded up immediately, which is bad for huge lists of items.
2.You need to know how big your items are, and they need to be the same size.

расквитаться:

1.It very easy to implement.

для получения дополнительной информации см. ссылку ниже

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ScrollView scrollView = new ScrollView(this);//ScrollView
    LinearLayout ll = new LinearLayout(this); //root LinearLayout
    ll.setOrientation(LinearLayout.HORIZONTAL);//with horizontal orientation
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,1f);
    LinearLayout l2 = new LinearLayout(this); //sub linearlayout
    l2.setOrientation(LinearLayout.VERTICAL);//with vertical orientation
    l2.setLayoutParams(layoutParams);
    LinearLayout l3 = new LinearLayout(this); //sub linearlayout
    l3.setOrientation(LinearLayout.VERTICAL);//with vertical orientation
    l3.setLayoutParams(layoutParams);
    int totalvalues=41;     //i take count as 41
    for(int i=0;i<totalvalues;i++){  // add the buttons in the layout based on condition
        Button okButton=new Button(this);
        okButton.setText("Button"+i);
        if(i<=totalvalues/2){
        l2.addView(okButton);
        }
        else{
        l3.addView(okButton);   
        }
    }
    ll.addView(l2);   //add sub linearlayout to root linearlayout
    ll.addView(l3);  //add sub linearlayout to root linearlayout

    scrollView.addView(ll); //add the root linearlayout to scrollview

    setContentView(scrollView);


}

Ответ 3

Вы пробовали:

DisplayMetrics metrics = getResources().getDisplayMetrics();
float dpW = 0f;
int pixelsW = (int) (metrics.density * dpW + 0.5f);
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(pixelsW, LayoutParams.WRAP_CONTENT, 1f);
TextView txt = new TextView(MainActivity.this);
ImageView img = new ImageView(MainActivity.this);
txt.setLayoutParams(lp);
img.setLayoutParams(lp);

Используя TableLayout LayoutParams, вы можете установить вес представления, который, как вам известно, должен быть 1. Мы также используем DisplayMetrics для преобразования float в формат "dp", используемый в xml.

EDIT:

Вы также можете установить этот LayoutParams в LinearLayout.