Я сейчас работаю над клоном визга и создал RecyclerView для отображения каждого ресторана. Теперь моя проблема в том, что все они ведут к одной и той же ссылке (первая). Это то, что я пробовал
url1 = button5.text.toString()
Toast.makeText(this, url1, Toast.LENGTH_SHORT).show();
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url1))
startActivity(intent)
и под связыванием
itemView.button5.text = restaurant.url
Я думаю, проблема в том, что button5 всегда первый в списке, но я не уверен, как определить, какой из них был нажат, и URL (текст) для него.
Полный код для адаптера
package com.example.yelpclone
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_restaurant.view.*
class RestaurantsAdapter(val context: Context, val restaurants: List<YelpRestaurant>) :
RecyclerView.Adapter<RestaurantsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_restaurant, parent, false))
}
override fun getItemCount() = restaurants.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val restaurant = restaurants[position]
holder.bind(restaurant)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
fun bind(restaurant: YelpRestaurant) {
//Display
itemView.tvName.text = restaurant.name
itemView.tvPrice.text = restaurant.price
itemView.tvDistance.text = restaurant.displayDistance()
itemView.tvNumReviews.text = restaurant.numReviews + " Reviews"
itemView.ratingBar.rating = restaurant.rating.toFloat()
itemView.Address.text = restaurant.location.address
itemView.tvCategory.text = restaurant.categories[0].title
itemView.button5.text = restaurant.url
//image
Picasso
.get()
.load(restaurant.imageUrl)
.resize(100, 100)
.centerCrop()
.into(itemView.imageView);
}
}
}
Полный код для действия
package com.example.yelpclone
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_restaurant_list.*
import kotlinx.android.synthetic.main.item_restaurant.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
private const val TAG = "RestaurantListActivity"
private const val BASE_URL = "https://api.yelp.com/v3/"
private const val API_KEY = "TZIrQEJTwJb4_Fyc6Ph1uKEkhzqizWg9TSTKO0Lyz9fbuRcfQVg4y7ArPvR4VLmlhkSYw6urRhVNwyykTGt8KDuTb3oZ5VPSj4kSx9QoUGL1wvDx4MSJvYxURwBzXnYx"
class RestaurantListActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_restaurant_list)
//Set up Layout
val restaurants = mutableListOf<YelpRestaurant>()
val adapter = RestaurantsAdapter(this,restaurants)
rvRestaurants.adapter = adapter;
rvRestaurants.layoutManager = LinearLayoutManager(this)
//Set up retrofit
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
//Call Yelp API
val yelpService = retrofit.create(YelpService::class.java)
yelpService.searchRestaurants("Bearer $API_KEY", searchTerm, inputLocation).enqueue(object : Callback<YelpSearchResult>{
override fun onResponse(
call: Call<YelpSearchResult>,
response: Response<YelpSearchResult>
) {
Log.i(TAG,"onResponse $response")
val body = response.body()
if (body == null){
Log.w(TAG, "Did not receive valid response body from Yelp API... exiting")
}
if (body != null) {
restaurants.addAll(body.restaurants)
}
adapter.notifyDataSetChanged()
}
override fun onFailure(call: Call<YelpSearchResult>, t: Throwable) {
Log.i(TAG,"onFailure $t")
}
})
}
fun goLink(view: View){
url1 = button5.text.toString()
Toast.makeText(this, url1, Toast.LENGTH_SHORT).show();
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url1))
startActivity(intent)
}
}
Класс данных
package com.example.yelpclone
import com.google.gson.annotations.SerializedName
data class YelpSearchResult(
@SerializedName("total") val total: Int,
@SerializedName("businesses") val restaurants: List<YelpRestaurant>
)
data class YelpRestaurant(
val name: String,
val rating: Double,
val price: String,
val categories: List<YelpCategory>,
val location: YelpLocation,
val url: String,
val id: String,
@SerializedName("review_count") val numReviews: String,
@SerializedName("distance") val distanceInMeters: Double,
@SerializedName("image_url") val imageUrl: String
) {
fun displayDistance(): String{
val milesPerMeter = .000621371
val distanceInMiles = "%.2f".format(distanceInMeters * milesPerMeter)
return "$distanceInMiles mi"
}
}
data class YelpCategory(
val title: String
)
data class YelpLocation(
@SerializedName("address1") val address: String
)