Tob*_*s D 1 android scrollview kotlin
如何在代码中创建一个动态添加 TextViews 的 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>
Run Code Online (Sandbox Code Playgroud)
作为布局文件,这是我的 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++
Run Code Online (Sandbox Code Playgroud)
但现在我收到错误:
java.lang.IllegalStateException: 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>
Run Code Online (Sandbox Code Playgroud)
但是,情况并非如此,因为您已经LinearLayout在布局的根目录中,因此,您可能需要考虑将内容ScrollView作为根目录放置在LinearLayout.
http://developer.android.com/reference/android/widget/ScrollView.html
| 归档时间: |
|
| 查看次数: |
10168 次 |
| 最近记录: |