android - 如何在 kotlin 中制作 ScrollView
问题描述
如何制作一个在代码中动态添加 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>
作为布局文件,这是我的 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 只能承载一个直接子级
解决方案
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
推荐阅读
- aws-lambda - Alexa SDK Card - 如何更改卡片中显示的文本的字体大小和字体类型
- java - ImageIO.read 找不到移动到子文件夹的文件
- c# - 调用在基泛型类中声明的非泛型方法会引发异常并带有消息
- ruby-on-rails - 发生 Ajax 请求时的 before_action 钩子
- flutter - 在 Flutter 中,我怎样才能更改一些小部件并看到它动画到它的新大小?
- r - 如何删除零值,直到第一个非零值出现在 R 数据帧中?
- list - 如何在闪亮的应用程序中呈现列表
- sql - SQL Server Order By isnull 意外结果
- amazon-web-services - AWS Cloudformation 将 API 密钥链接到 API 网关
- vim - Command-T 不会为 Vim 编译