代码之家  ›  专栏  ›  技术社区  ›  chicken9301

如何在片段中更改文本视图中的文本值。科特林

  •  0
  • chicken9301  · 技术社区  · 2 年前

    有人知道在片段中更改textview文本值的方法吗。我尝试过findviewbyid,但我认为这在处于崩溃状态时不起作用。有人知道如何识别文本视图并更改其文本值吗。谢谢

    
    class Home : Fragment() {
    
        override fun onCreateView(
    
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
            val view =  inflater.inflate(R.layout.fragment_home, container, false)
    
            val queue = Volley.newRequestQueue(view.context)
            val url = "https://io.adafruit.com/api/v2/alex9301/feeds/test-data/data" //URL
            var urlStuff = ""
    
            val stringRequest = StringRequest(Request.Method.GET, url,
                { response ->
                    // Display the first 500 characters of the response string.
                    urlStuff = response
                    val jsonArray = JSONTokener(urlStuff).nextValue() as JSONArray
                    val id = jsonArray.getJSONObject(0).getString("value") // Get data
                    Log.i("Val: ", id)
    
                    //Updating info on app
                    val textView = view.findViewById(R.id.temp)                 
                    textView.text = "My Text"
    
    
                },
                { Log.i("b", "That didn't work!") })
            queue.add(stringRequest)
            return view
    
        }
    
    
    }
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Mario Huizinga    2 年前

    findViewById也可以在片段中工作,如下所示:

    val view =  inflater.inflate(R.layout.fragment_home, container, false)
    val textView: TextView = view.findViewById(R.id.temp)
    textView.text = "My Text"