android - 如何在 Fragment View 中访问 findViewById - Kotlin

标签 android android-fragments kotlin

我正在尝试显示来自服务器的 json 文件的数据列表。

当我尝试通过 Id 选择 View 时,它会抛出错误。


import android.os.AsyncTask
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import android.widget.ProgressBar
import kotlinx.android.synthetic.*
import org.json.JSONObject
import java.net.URL

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class HomeFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    var dataList = ArrayList<HashMap<String, String>>()
    private var res: View? = null ;


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        this.res  = inflater.inflate(R.layout.fragment_home, container, false);

        return res;
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        fetchJsonData().execute()

    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment HomeFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            HomeFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }

    /**
     * Asyntask for getting list view
     * from and point
     */

    inner class fetchJsonData() : AsyncTask<String, Void, String>() {
        override fun onPreExecute() {
            super.onPreExecute()
        }

        override fun doInBackground(vararg params: String?): String? {
            return URL("https://www.androdocs.com/files/uploads/original/sample-json-data-1567767983.txt").readText(
                Charsets.UTF_8
            )
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)

            super.res.findViewById<ProgressBar>(R.id.loader).visibility = View.GONE

            val jsonObj = JSONObject(result)
            val usersArr = jsonObj.getJSONArray("users")
            for (i in 0 until usersArr.length()) {
                val singleUser = usersArr.getJSONObject(i)

                val map = HashMap<String, String>()
                map["name"] = singleUser.getString("name")
                map["age"] = singleUser.getString("age")
                map["city"] = singleUser.getString("city")
                map["image"] = singleUser.getString("image")
                dataList.add(map)
            }

            findViewById<ListView>(R.id.listView).adapter =
                CustomAdapter(this@HomeFragment, dataList)

        }
    }
}


以下是我的代码。

在 AsynTask 中获取 Json 后,我需要停止加载器并传递加载的数据。这就是抛出错误的地方。

最佳答案

您可以尝试这种方法。

lateinit var progressBar: ProgressBar // Global declare

然后

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        progressBar = view.findViewById(R.id.loader)
        // You can declare your listview here
        fetchJsonData().execute()    
    }

然后

 override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            progressBar.visibility = View.GONE

关于android - 如何在 Fragment View 中访问 findViewById - Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452390/

相关文章:

android - Gradle - 根据产品风格构建 sass(多文件夹)

android - 如何在多 fragment Activity 中处理 onContextItemSelected?

android - 从 Activity 获取嵌套 fragment

android - 带有 Kotlin 的 Android 中的 HTTP 请求

安卓邮件发送验证

android - Android 8以上版本Delphi无法启动Android Service

android - 日期选择器对话框无法切换到 Android 7.0 设备上的微调器

android - 如何为 fragment 中的不同方向设置不同的布局

kotlin - 是否可以编写 "double"扩展方法?

kotlin - 上下循环