You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ScrollView内嵌TextView插入新文本后无法居中问题如何解决?

问题原因分析
  • 居中属性被覆盖:代码中先设置了resultdop.textAlignment = View.TEXT_ALIGNMENT_CENTER,紧接着又赋值为View.TEXT_ALIGNMENT_GRAVITY,前面的居中设置直接被覆盖失效。
  • UI操作位置错误:给resultdop设置居中属性的代码写在doAsync异步块外面,而异步请求是耗时操作,属性设置先执行,后续在子线程更新resultdop文本时,部分设备上会导致原本的居中属性被重置,且在子线程直接操作TextView更新UI本身就不符合安卓开发规范,是属性不生效的核心原因。
  • 冗余属性冲突:同时给ScrollView、LinearLayout、TextView都设置了textAlignment,多层属性叠加会产生冲突。
修复方案
  1. 修正业务代码逻辑,将所有UI操作切换到主线程执行,删除重复覆盖的错误赋值,修改后代码如下:
if (resultdop.text == ""){
    val city: String = userfield.text.toString()
    val key = "e9c95bab1d070877909fd3e55310c60c"
    val url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$key&units=metric&lang=ru"
    val urls = "https://api.openweathermap.org/data/2.5/forecast?q=$city&appid=$key&units=metric&lang=ru"
    doAsync {
        val apiresponse = URL(url).readText()
        val weather = JSONObject(apiresponse).getJSONArray("weather")
        val desc = weather.getJSONObject(0).getString("description")
        val main = JSONObject(apiresponse).getJSONObject("main")
        val temp = main.getString("temp")
        val apiresponses = URL(urls).readText()
        val list = JSONObject(apiresponses).getJSONArray("list")
        var otvet = ""
        for (i in 1 until list.length()){
            val obj = list.getJSONObject(i)
            val tempd = obj.getJSONObject("main").getInt("temp")
            val weatherd = obj.getJSONArray("weather")
            val descd = weatherd.getJSONObject(0).getString("description")
            val time = obj.getString("dt_txt")
            otvet += "$time \n $tempd ℃, $descd \n \n"
        }
        // 所有UI操作切到主线程执行
        uiThread {
            resultfield.text = "Температура: $temp ℃, $desc"
            resultdop.text = otvet
            // 只保留必要的居中设置,不要重复覆盖
            resultdop.gravity = Gravity.CENTER_HORIZONTAL
            resultdop.textAlignment = View.TEXT_ALIGNMENT_CENTER
        }
    }
}
  1. 优化XML布局,删除父布局冗余的textAlignment属性,避免层级冲突:
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/result">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/resultdop"
            android:textSize="20sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-light"
            android:gravity="center_horizontal"
            android:textAlignment="center"
            android:textColor="@color/white" />
    </LinearLayout>
</ScrollView>

内容的提问来源于stack exchange,提问作者Roych_Sanderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 05:06:03