Данные API во фрагменте kotlin - PullRequest
1 голос
/ 06 февраля 2020

Я пытаюсь использовать Drawer activity, кажется, у него есть 3 файла, чтобы просто показать простой текст как This is home Fragment: |

В любом случае, я отследил все эти файлы и нашел fragment_home.xml, HomeFragment.kt и HomeViewModel.kt

Вопрос

Как мне вызывать фрагменты данных API через код?

Код

my code

На основании android студийной документации это код, который я должен использовать для получения данных API.

val textView = findViewById<TextView>(R.id.TextView)

// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://example.com/api/listings"

// Request a string response from the provided URL.
val stringRequest = StringRequest(
    Request.Method.GET, url,
    Response.Listener<String> { response ->
        // Display the first 500 characters of the response string.
        textView.text = "Response is: ${response.substring(0, 500)}"
    },
    Response.ErrorListener { textView.text = "That didn't work!" })

// Add the request to the RequestQueue.
queue.add(stringRequest)

PS: я пробовал этот код выше в пустой деятельности, она работает

HomeViewModel.kt

class HomeViewModel : ViewModel() {

    private val _text = MutableLiveData<String>().apply {
        value = "This is home Fragment"
    }
    val text: LiveData<String> = _text
}

HomeFragment.kt

class HomeFragment : Fragment() {

    private lateinit var homeViewModel: HomeViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel::class.java)
        val root = inflater.inflate(R.layout.fragment_home, container, false)
        val textView: TextView = root.findViewById(R.id.text_home)
        homeViewModel.text.observe(this, Observer {
            textView.text = it
        })
        return root
    }
}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_home"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Пожалуйста, обратите внимание, прежде чем пытаться отдать голос: Я знаю, что этот вопрос, вероятно, очень простой c вопрос, но обратите внимание что я впервые использую фрагменты (в основном, newb ie в android studio), так что да, мои вопросы вроде основы c:)

1 Ответ

1 голос
/ 06 февраля 2020

для вызова API из фрагмента, вы можете сделать

class HomeFragment : Fragment() {

  private lateinit var homeViewModel: HomeViewModel

            override fun onCreateView(
                inflater: LayoutInflater,
                container: ViewGroup?,
                savedInstanceState: Bundle?
            ): View? {
                homeViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)

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

                val textView: TextView = root.findViewById(R.id.text_home)

                //calling the API
                callAPIDemo(textView)

               // homeViewModel.text.observe(this, Observer {
               //     textView.text = it
               // })

                return root
            }

     fun callAPIDemo(textView: TextView) {
        // Instantiate the RequestQueue.
        val queue = Volley.newRequestQueue(activity)
        val url = "https://example.com/api/listings"

        // Request a string response from the provided URL.
        val stringRequest = StringRequest(
                Request.Method.GET, url,
                Response.Listener<String> { response ->
                    // Display the first 500 characters of the response string.
                    textView.text = "Response is: ${response.substring(0, 500)}"
                },
                Response.ErrorListener { textView.text = "That didn't work!" })

        // Add the request to the RequestQueue.
        queue.add(stringRequest)
    }

        }
...