如何在代码中创建一个动态添加文本视图的ScrollView?现在我有:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create TextView"
/>
<ScrollView
android:id="@+id/Scroll"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
作为布局文件,这作为我的kotlin文件:
class Abfahrtsmonitor : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.abfahrtsmonitor)
// Variable for counting text view
var counter: Int = 1;
// Set a click listener for button widget
button.setOnClickListener{
// Create a new TextView instance programmatically
val text_view: TextView = TextView(this)
// Creating a LinearLayout.LayoutParams object for text view
var params : LayoutParams = LayoutParams(
LayoutParams.MATCH_PARENT, // This will define text view width
LayoutParams.WRAP_CONTENT // This will define text view height
)
// Display some text on the newly created text view
text_view.text = "Hi, i am a TextView. Number : $counter"
// Finally, add the text view to the view group
Scroll.addView(text_view)
// Increment the counter
counter++
但现在我收到了错误:
java.lang.IllegalStateException:ScrollView只能托管一个直接子项
ScrollView
本身只能容纳一个孩子,在这种情况下你的布局。布局可以包含多个视图,您应该将TextView
s添加到布局,而不是ScrollView
。
java.lang.IllegalStateException:
ScrollView
只能托管一个直接子项
ScrollView
只能容纳一个孩子,这意味着它只能容纳一个视图,因为它是直接的孩子,所以这样的东西会有所帮助:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
// Content in here ...
</LinearLayout>
</ScrollView>
但是,情况并非如此,因为你已经在布局的根目录中有LinearLayout
所以,你可能想考虑将ScrollView
作为根和LinearLayout
内的内容。 http://developer.android.com/reference/android/widget/ScrollView.html