Android: раздувание линейных представлений в ScrollView - PullRequest
1 голос
/ 29 мая 2011

Итак, у меня есть класс, который получает элементы из базы данных, а затем помещает их в макет и раздувает.Это перебирает каждый элемент в базе данных, раздувая новый макет для каждого элемента.Это в конечном итоге распространяется за пределы области просмотра и будет нуждаться в полосе прокрутки, которая, как я предполагаю, будет ScrollView.Я пробовал много разных способов и не могу заставить его просматривать весь контент.Пожалуйста, сообщите.

Java:

View myView = linflater.inflate(R.layout.myviews, null);

TextView tvQuote = (TextView) myView.findViewById(R.id.lblQuote);
//Set an id to know which quote is in use
tvQuote.setId(i);
TextView tvShared = (TextView) myView.findViewById(R.id.lblShared);
TextView tvSaid = (TextView) myView.findViewById(R.id.lblSaid);

//Change name dynamically
tvQuote.setText((strQuote).toString());
tvShared.setText(("Shared by: " + strFName + " " + strLInitial).toString());
tvSaid.setText(("Said by: " + strFNameSaid + " " + strLInitialSaid).toString());

main.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        android:orientation="vertical" 
        android:id="@+id/myMainLayout" 
        android:layout_width="fill_parent" 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_height="wrap_content">   
    <TextView 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" 
        android:text="Quoter" 
        android:id="@+id/lblTitle" 
        android:textSize="16px" 
        android:padding="5px" 
        android:textStyle="bold" 
        android:gravity="center_horizontal">
    </TextView>
</LinearLayout>

myviews.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">


        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <TextView 
                android:id="@+id/lblQuote" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
        </LinearLayout>

        <LinearLayout 
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <TextView 
                android:id="@+id/lblShared" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <TextView 
                android:id="@+id/lblSaid" 
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content"
                android:layout_weight="1"/> 
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
          <TextView
            android:text=" "
            android:textSize="1pt"
            android:background="#6F7285"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>     
        </LinearLayout>
</LinearLayout>

Что былучшее решение для прокрутки всех этих раздутых макетов?

Ответы [ 4 ]

4 голосов
/ 29 мая 2011

Похоже, вы делаете слишком много работы. Если ваши данные находятся в базе данных SQLite, вы можете использовать SimpleCursorAdapter со своим ListView, который сделает за вас тяжелую работу:

public class MyListActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // The my_list_activity layout is the container for each
        // item in the list.
        setContentView(R.layout.my_list_activity);

        // Create a database cursor for the data you want to query.
        // Assumes your data is accessible via a ContentProvider.

        // Note: db.CONTENT_URI is whatever URI your ContentProvider uses,
        // and db.COL1 etc are constants that would name the columns you want.
        cursor = getContentResolver().query(db.CONTENT_URI,
            new String[] { db._ID, db.COL1, db.COL2, db.COL3 },
            null, null, null);

        // Bind the value in db.COL1 to the resource with the id text1, and so
        // on for the other two columns.
        //
        // Assumes that the view has TextViews with IDs text1, text2, and text3.
        String[] from= new String[] { db.COL1, db.COL2, db.COL3 };
        int[] to = new int[] { R.id.text1, R.id.text2, R.id.text3 };

        // Create the adapter, bound to the cursor, layout, and the mapping from
        // column name to TextView ID.
        //
        // Assumes a layout called my_list_activity_item exists, with at least
        // 3 views called text1, text2, and text3.
        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
            R.layout.my_list_activity_item, cursor, from, to);

        setListAdapter(mAdapter);
    }
}

Если ваших данных нет в базе данных SQLite, посмотрите на другие классы, производные от android.widget.BaseAdapter, чтобы узнать, подходит ли вам один из них.

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

Я обнаружил, что добавление ScrollView в main.xml было исправлением.Спасибо за вашу помощь, ребята.Я все еще хотел бы знать, делаю ли я это неправильно все же.

0 голосов
/ 29 мая 2011

Я думаю, что быстрый ответ заключается в том, что вам нужно ScrollView вокруг всех этих LinearLayout с, чтобы вы могли фактически прокрутить (у вашего первого LinearLayout есть height = wrap_content).Длинная версия состоит в том, что вы, вероятно, делаете это неправильно, и вместо этого вам следует использовать ListView и Adapter.

0 голосов
/ 29 мая 2011

Вы используете слишком много linearlayouts в вашем myviews.xml. Это должно помочь вам:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <TextView 
            android:id="@+id/lblQuote" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:text="text"
            />
        <TextView 
            android:id="@+id/lblShared" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_below="@id/lblQuote" 
            android:text="text"
            />
        <TextView 
            android:id="@+id/lblSaid" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_below="@id/lblQuote" 
            android:layout_alignParentRight="true"
            android:text="text"
            /> 
        <TextView
            android:text="text "
            android:background="#6F7285"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/lblShared" 
            />     
    </RelativeLayout>
</ScrollView>

Я добавил текст-заполнитель, чтобы вы могли его видеть. Удалите все, что вам не нужно.

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