Kotlin 设置文本

Kotlin set text

我想用 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()
   }
)

我也试过 这样 mMonth.text = responseObject.month none 成功了。

更新

这里问的是我的 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)
}

可能是因为你将视图放大了两次。只需在 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()
})

你正在膨胀片段视图两次,使用你第一次膨胀的相同视图:

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

使用这个 'root' 来查找文本视图而不是这样做

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