Android scrollview不适用于动态内容

时间:2017-07-13 20:00:09

标签: java android scrollview android-linearlayout android-relativelayout

我动态创建来自我的JSON数据的表行和textview,这是我从api获得的。目前数据显示正确,但不知何故我的滚动视图不起作用。它不会滚动。我确实添加了一个ScrollView,但我想我在那里做错了。

我的Xml:

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

    <ScrollView android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:orientation="vertical"
        xmlns:android="http://schemas.android.com/apk/res/android">

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

            <TableLayout
                android:id="@+id/tlMarksTable"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" >

            </TableLayout>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

我生成视图的部分看起来像这样:

jsonArray = new JSONArray(result);

TableRow tableRow = new TableRow(context);
setContentView(tableRow);
tableRow.setOrientation(LinearLayout.VERTICAL);

for(int i= 0; i < jsonArray.length(); i++) {
    JSONObject jsonobject = jsonArray.getJSONObject(i);
    String id         = jsonobject.getString("id");
    String content    = jsonobject.getString("content");

    TextView textView = new TextView(context);
    textView.setText(content);
    if (Build.VERSION.SDK_INT < 23) {
        textView.setTextAppearance(getApplicationContext(), R.style.boldText);
    } else {
        textView.setTextAppearance(R.style.boldText);
    }
    textView.setBackgroundResource(R.color.highlightedTextViewColor);
    textView.setPadding(10, 10, 10, 10);
    textView.setTextSize(getResources().getDimension(R.dimen.joke_content_font_size));
    tableRow.addView(textView);
}

3 个答案:

答案 0 :(得分:0)

让您的内部组件配置如下:

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

            <TableLayout
                android:id="@+id/tlMarksTable"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >

            </TableLayout>

        </LinearLayout>

顺便说一下外部RelativeLayout ViewGroup没有做太多的事情

答案 1 :(得分:0)

我在这里看到的主要问题是封装了您的LinearLayout的{​​{1}}已TableLayout。这意味着android:layout_height="match_parent"的内部子项将与父项具有相同的高度,从而导致非滚动布局。

为什么不尝试删除ScrollView,并将LinearLayout作为唯一的孩子?请记住将该孩子的身高设置为TableLayout

顺便说一句,我建议使用android:layout_height="wrap_content"来显示大量数据。

最后一件事:不需要在每个布局声明中声明xml命名空间(ListView)。只有在根元素处有一个声明才会没问题;)

答案 2 :(得分:0)

为什么不使用Recyclerview? 您应该使用改造来使用WS