简体   繁体   English

如何在片段视图中访问 findViewById - Kotlin

[英]How to access findViewById in Fragment view - Kotlin

I am trying to show a list of data coming from a json file from a server.我正在尝试显示来自服务器的 json 文件的数据列表。

When I try to select the view by Id it throws error.当我尝试 select 时,Id 的视图会引发错误。


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)

        }
    }
}


Following is my code.以下是我的代码。

After fetching the Json in the AsynTask I need to stop the loader and pass the loaded data.在 AsynTask 中获取 Json 后,我需要停止加载程序并传递加载的数据。 That's where its throwing error.这就是它的抛出错误。

You can try this approach.你可以试试这个方法。

lateinit var progressBar: ProgressBar // Global declare

Then然后

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()    
    }

Then然后

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM