繁体   English   中英

得到Retrofit条数据。 Android. Kotlin

[英]Get Retrofit data. Android. Kotlin

我是编程新手,需要您的帮助。 任务是这样的:我从想要获取角色 ID 的服务发出请求,但它不起作用。 下面是代码!

Api

@GET("people/{id}")
    suspend fun getCharacter(@Path("id") id: Int): Response<Characters>

资料库

suspend fun getCharacters(id: Int) =
        RetrofitBuilder.api.getCharacter(id)

视图模型

class DetailViewModel : ViewModel() {
    var repository = StarWarsRepository()
    private val _response = MutableLiveData<Characters>()
    val character: LiveData<Characters>
        get() = _response


    fun getCharacter(id: Int) {
        viewModelScope.launch {
            repository.getCharacters(id).let { response ->

                if (response.isSuccessful) {
                    _response.postValue(response.body())
                } else {
                    Log.d("tag", "Error: ${response.code()}")
                }
            }
        }
    }
}

片段在第 27 行中,我调用了 function getCharacterViewModel(),您需要在此处指定 ID。 我需要在这个参数中指定什么,以便当我点击列表中的一个角色时,我有关于他的信息?


class DetailFragment : Fragment() {
    private var _binding: FragmentDetailBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: DetailViewModel


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentDetailBinding.inflate(inflater, container, false)
        val view = binding.root
        viewModel = ViewModelProvider(this)[(DetailViewModel::class.java)]
        getCharacterViewModel()
        return view
    }

    private fun getCharacterViewModel(id: Int){
        viewModel.getCharacter(id)
        viewModel.character.observe(this, { name ->
            binding.birth.text = name.birth_year
            binding.name.text = name.characters
            binding.mass.text = name.mass
            binding.mass.text = name.height

        })
    }

}

您想单击一个列表中的项目并获取有关该项目的信息,对吗?

你需要在清单上工作。 它是 RecyclerView 吗? 例如,如果您的列表是一个 RecyclerView,您将需要修改您的适配器。

在适配器上创建更多参数

class YourAdapter (..., val onItemClick: (Character) -> Unit){
   //Your Code Here
}

并且,在您的适配器上的“onBind”方法上,在您的视图上设置点击侦听器并调用

onItemClick(<clickedItemHereAsParam>))

在里面。

检查此 anwser 的更多详细信息: How do I implement onClickListener to a recyclerView to open a new fragment when clicked

暂无
暂无

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

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