如何修复包含Textview的线性布局的Scrollview

时间:2019-07-12 22:27:41

标签: java android-studio

我目前有一个程序使用线性布局,该程序包含一个Textview,该Textview中填充了x个值(取决于在单独活动中确定的arrayList大小),但是Scrollview无法正常工作。

由于Scrollview只能有一个直接子代,所以我将线性布局与TextView嵌套在其中;但是,当我将它们都包装在Scrollview中时,线性布局仍然无法滚动

//This is what I am using to populate the Linear Layout that I'm trying to make scrollable
TextView DisplayString = (TextView)findViewById(R.id.stringNumsCon1);
        LinearLayout LinContainer = (LinearLayout)findViewById(R.id.LinLay);

        Intent intent = getIntent();
        ArrayList<String> timerVals = (ArrayList<String>)getIntent().getSerializableExtra("timerVals");

        DisplayString.setTextSize(15);
        DisplayString.setTextColor(Color.BLACK);
        for(int i=0; i<timerVals.size(); i++){
            DisplayString.append(timerVals.get(i));
            DisplayString.append("\n");
        }

//This is how I am trying to make it scrollable within the xml
<ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/LinLay"
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="391dp">
            <TextView
                android:id="@+id/stringNumsCon1"
                android:layout_width="match_parent"
                android:layout_height="391dp"
                android:orientation="vertical">
            </TextView>

        </LinearLayout>
    </ScrollView>

我希望这可以使“线性布局”部分可滚动,但是我可以看到在实际实现此代码时数据被切断并且无法访问

1 个答案:

答案 0 :(得分:1)

您将不需要ScrollView,也不需要LinearLayout。从您的布局中删除它们。 您所需要做的全部是在xml的TextView中设置的:

android:scrollbars = "vertical"

所以您最终的xml布局将是:

<TextView
   android:id="@+id/stringNumsCon1"
   android:layout_width="match_parent"
   android:layout_height="391dp"
   android:orientation="vertical"
   android:scrollbars = "vertical" />

然后在活动/片段的onCreate中设置移动方法,如下所示:

Java

DisplayString.setMovementMethod(new ScrollingMovementMethod());

科特林

DisplayString.movementMethod = ScrollingMovementMethod()

P.S.1 :您可以找到原始答案here
P.S.2::考虑对变量名使用驼峰式命名约定。例如。使用displayString而不是DisplayString。