Reputation: 129
I try to make a ScrollView to act like a ListView. So every row will be a TextView added dynamically. but the program crashes. I have a ScrollView inside a LinearLayout. What i do wrong? Thanks.
Here is my code
scroll = (ScrollView)findViewById(R.id.scrollView1);
layout = (LinearLayout) findViewById(R.id.LinearLayout1);
layout.setBackgroundColor(Color.TRANSPARENT);
TextView[] tx = new TextView[10];
for (int i = 0; i < 10; i++) {
tx[i] = new TextView(HelloWorldActivity.this);
tx[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
tx[i].setText("This is the textviewNo" + i);
layout.addView(tx[i]);
}
scroll.addView(layout);
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/timeflag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="50sp"
android:gravity="center"/>
<Button
android:id="@+id/pause"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/timeflag"
android:layout_marginTop="37dp"
android:text="Start" />
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/pause"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ScrollView>
</LinearLayout>
</RelativeLayout>
Upvotes: 0
Views: 4040
Reputation: 86948
You are trying to add LinearLayout1
as its own child's child (being your own grandfather, is a confusing notion).
Change you XML around like this:
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="@+id/pause"
>
<LinearLayout
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
Upvotes: 1
Reputation: 3893
You cannot add views to a scrollview. You can only add them to a viewgroup, like linear or relativelayout.
It is not exactly clear what you are trying to achieve, but what is wrong with using a listview for this? You could set a max height on the listview. Or you could try wdziemia's suggestion
Upvotes: 0
Reputation: 1459
A scrollView Can only have one child. If you try to add more than 1 child to the scroll view then it will crash. You should have the LinearLayout inside of the scrollview and then dynamically add textViews to the linear layout.
Upvotes: 3