【问题标题】:Kotlin set textKotlin 设置文本
【发布时间】:2021-02-01 14:11:17
【问题描述】:

我想用 API 返回的数据更改 TextView 中的静态字符串,但它不会更改值。

代码

val stringRequest = StringRequest(
  Request.Method.POST, url,
  Response.Listener<String> { response ->
   val responseObject = Gson().fromJson(response, DriverIncome::class.java)

     val view = View.inflate(context, R.layout.fragment_home, null)
     val mMonth: TextView = view.findViewById(R.id.this_month_value) as TextView
     val mTotal: TextView = view.findViewById(R.id.total_price_value) as TextView

     mMonth.setText(responseObject.month)
     mTotal?.setText(responseObject.total)
   },
   Response.ErrorListener { error ->
     Toast.makeText(context,"Something went wrong", Toast.LENGTH_SHORT)
     .show()
   }
)

我也尝试了this answer,但这样mMonth.text = responseObject.month 都不起作用。

更新

这里被问到是我的 XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <ImageView
        android:id="@+id/main_header"
        android:layout_width="483dp"
        android:layout_height="233dp"
        android:contentDescription="@string/headerImage"
        android:src="@drawable/main_header"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/my_image_view"
        android:layout_width="80dp"
        android:layout_height="81dp"
        android:layout_marginTop="60dp"
        android:contentDescription="@string/avatar"
        android:maxWidth="25dp"
        android:maxHeight="25dp"
        app:layout_constraintBottom_toBottomOf="@+id/main_header"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.879"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.043"
        tools:srcCompat="@tools:sample/avatars" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="224dp"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="@string/name"
        android:textColor="#FFFFFF"
        app:layout_constraintBottom_toTopOf="@+id/mainname"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.042"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/mainname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="64dp"
        android:text="@string/launryku"
        android:textColor="#FFFFFF"
        android:textFontWeight="@integer/fifty"
        android:textSize="30sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/maindescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="12dp"
        android:text="@string/fasteasyclean"
        android:textColor="#FFFFFF"
        android:textFontWeight="@integer/thirthy"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="@+id/main_header"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/mainname"
        app:layout_constraintVertical_bias="0.043" />

    <ImageView
        android:id="@+id/bell"
        android:layout_width="24dp"
        android:layout_height="17dp"
        android:layout_marginTop="16dp"
        android:contentDescription="@string/notifications"
        android:src="@drawable/notification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.957"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.cardview.widget.CardView
        android:id="@+id/this_month_income"
        android:layout_width="195dp"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintTop_toBottomOf="@+id/main_header"
        tools:ignore="MissingConstraints">

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:stretchColumns="1">

            <TableRow>

                <ImageView
                    android:id="@+id/month_image"
                    android:layout_width="0dp"
                    android:layout_height="100dp"
                    android:layout_column="1"
                    android:contentDescription="@string/month_image"
                    android:padding="3dip"
                    android:src="@drawable/month_income" />
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/thismonth"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:padding="3dip"
                    android:text="@string/thismonth"
                    android:textAlignment="center" />
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/this_month_value"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:gravity="bottom"
                    android:padding="3dip"
                    android:text="@string/this_month_value"
                    android:textAlignment="center"
                    tools:ignore="RtlCompat" />
            </TableRow>
        </TableLayout>
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:id="@+id/total_income"
        android:layout_width="195dp"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:textAlignment="center"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/main_header"
        tools:ignore="MissingConstraints">

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:stretchColumns="1">

            <TableRow>

                <ImageView
                    android:id="@+id/totla_image"
                    android:layout_width="0dp"
                    android:layout_height="100dp"
                    android:layout_column="1"
                    android:contentDescription="@string/total_image"
                    android:padding="3dip"
                    android:src="@drawable/total_income" />
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/total_price"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:layout_gravity="bottom"
                    android:padding="3dip"
                    android:text="@string/totalincome"
                    android:textAlignment="center"
                    tools:ignore="RtlCompat" />
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/total_price_value"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_column="1"
                    android:padding="3dip"
                    android:text="@string/total_price_value"
                    android:textAlignment="center" />
            </TableRow>
        </TableLayout>
    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

更新 2

片段代码

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_home, container, false)
    callIncomeAPI()
    return root
}

private fun callIncomeAPI() {
    val queue = Volley.newRequestQueue(context)

    var session = SessionManager(context)
    session.checkLogin()
    var user = session.getUserDetails()
    var token: String? = user.get(SessionManager.KEY_ACCESS_TOKEN)
    val tokenFull = "Bearer $token"

    val url = "https://example.com/api/incomes/$tokenFull"
    // Request a string response from the provided URL.
    val stringRequest = StringRequest(
        Request.Method.POST, url,
        Response.Listener<String> { response ->
            val responseObject = Gson().fromJson(response, DriverIncome::class.java)

            val view = View.inflate(context, R.layout.fragment_home, null)
            val mMonth: TextView = view.findViewById(R.id.this_month_value) as TextView
            val mTotal: TextView = view.findViewById(R.id.total_price_value) as TextView

            mMonth.setText(responseObject.month)
            mTotal.setText(responseObject.total)
        },
        Response.ErrorListener { error ->
            Toast.makeText(context,"Something went wrong", Toast.LENGTH_SHORT)
                .show()
        })
    // Add the request to the RequestQueue.
    queue.add(stringRequest)
}

【问题讨论】:

  • 看来你指的是错误的观点。
  • @rahat 你的意思是view.findViewById(R.id.this_month_value)?
  • 您需要清除两件事: 1. 如果响应来自服务器正确。 2.你指的是正见吗?并且还提供你的XML代码,这样会更容易理解问题。
  • @SoumikBhattacharjee 1. 数据正常是的。 2. 我不确定 3. 好的
  • @mafortis 你在 StringRequest 块内膨胀你的片段布局。这一行:val view = View.inflate(context, R.layout.fragment_home, null) 你确定这是你想要的吗?一般来说,你应该在 onCreateView() 方法上增加你的布局......

标签: android kotlin textview


【解决方案1】:

可能是因为您两次放大了视图。只需在onCreateView 中分配textview 即可正常工作。

private var mMonth: TextView
private var mTotal: TextView

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_home, container, false)
    mMonth: TextView = root.findViewById(R.id.this_month_value) as TextView
    mTotal: TextView = root.findViewById(R.id.total_price_value) as TextView
    callIncomeAPI()
    return root
}

然后设置文本:

val stringRequest = StringRequest(
Request.Method.POST, url,
Response.Listener<String> { response ->
    val responseObject = Gson().fromJson(response, DriverIncome::class.java)
    mMonth.setText(responseObject.month)
    mTotal.setText(responseObject.total)
},
Response.ErrorListener { error ->
    Toast.makeText(context,"Something went wrong", Toast.LENGTH_SHORT)
        .show()
})

【讨论】:

  • mMonth.setText(responseObject.month) 在 callIncomeAPI 内部未定义
  • @mafortis 您是否在全局级别设置了变量?查看我的代码,我在onCreateView 之外声明了变量
  • 哎呀 :) 再试一次
【解决方案2】:

您将片段视图膨胀两次,使用您首先膨胀的同一视图:

val root = inflater.inflate(R.layout.fragment_home, container, false)

使用这个“根”来查找文本视图而不是这样做

val view = View.inflate(context, R.layout.fragment_home, null)
view.findViewById(.....

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多