我目前在使用 <em><strong>addView()</strong></em> 方法时遇到问题,该方法在 <em><strong>LinearLayout</strong></em> 中创建了文本内容,但并不是将文本添加到我想要的动态创建并插入 <em><strong>LL</strong></em>(LinearLayout)中的 <em><strong>TextView()</strong></em> 组件内。
我已经通过设备上的运行应用,在“组件树”中观察到了这个问题的发生。
DashboardFragment.kt
package com.test.testapp
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
class DashboardFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_dashboard, container, false)
getUpdateList()
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
fun getUpdateList(){
val testinglayout: LinearLayout = requireView().findViewById(R.id.testinglayout)
val textView = TextView(activity)
textView.setText("Test")
testinglayout.addView(textView)
}
}
fragment_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/rmPaleTeal"
tools:context=".DashboardFragment">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/rmPaleTeal"
android:padding="15dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/dashboard_latest_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:text="Latest Updates"
android:textColor="@color/rmDarkBlue"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:id="@+id/testinglayout"
android:layout_below="@+id/dashboard_latest_title"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
参考图片:组件树
由于我对此感到困惑且在网上找不到合适的解决方案,所以任何帮助都将不胜感激。感谢您花时间阅读我的问题!