#java #android #android-recyclerview #android-cardview
#java #Android #android-recyclerview #android-cardview
Вопрос:
Я пытаюсь заполнить CardView
внутри a RecyclerView
. Хотя я могу регистрировать все значения адаптера (чтобы убедиться, что они не пустые) Я не могу заполнить ни одной в пользовательском интерфейсе. Вот код действия:
FoodActivity.class
public class FoodActivity extends AppCompatActivity
{
private RecyclerView foodView;
private List<Result> adapter_data;
private CustomPlacesAdapter adapter;
private LinearLayoutManager llm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
foodView = (RecyclerView)findViewById(R.id.foodRView);
adapter = new CustomPlacesAdapter(adapter_data);
adapter_data = new ArrayList<>();
llm = new LinearLayoutManager(this);
foodView.setLayoutManager(llm);
foodView.setAdapter(adapter);
doGetRequest("restaurants in los angeles airport");
}
private void doGetRequest(final String message)
{
ApiInterfacePlaces apiService =
ApiClientPlaces.getClient().create(ApiInterfacePlaces.class);
Call<PlacesPojo> call = apiService.getValues(message, Util.getKeyForPlaces());
call.enqueue(new Callback<PlacesPojo>()
{
@Override
public void onResponse(Call<PlacesPojo>call, Response<PlacesPojo> response)
{
try
{
Log.e("TAG","" response.body().toString());
List<Result> response_res = response.body().getResults();
adapter_data = response_res;
adapter.notifyDataSetChanged();
}
catch (Exception e)
{
Toast.makeText(FoodActivity.this, "Check data connection", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<PlacesPojo> call, Throwable t) {
// Log error here since request failed
Log.e("FAILURE", t.toString());
}
});
}
}
Вот код для RecyclerView
адаптера:
CustomPlacesAdapter.class
public class CustomPlacesAdapter extends RecyclerView.Adapter<CustomPlacesAdapter.HotelsViewHolder>
{
private DataHolder d2 = new DataHolder();
public class HotelsViewHolder extends RecyclerView.ViewHolder
{
private TextView hotelName;
private Typeface face;
private ImageView hotel_logo;
private Context mcontext;
HotelsViewHolder(View itemView)
{
super(itemView);
mcontext = itemView.getContext();
hotelName = (TextView)itemView.findViewById(R.id.hotelName);
face = Typeface.createFromAsset(itemView.getContext().getAssets(), "Fonts/Roboto-Regular.ttf");
hotelName.setTypeface(face);
hotel_logo = (ImageView)itemView.findViewById(R.id.logoOfHotel);
}
}
private static class DataHolder
{
List<Result> feeds;
}
public CustomPlacesAdapter(List<Result> feeds)
{
this.d2.feeds = feeds;
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public HotelsViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.food_item, viewGroup, false);
HotelsViewHolder pvh = new HotelsViewHolder(v);
return pvh;
}
@Override
public void onBindViewHolder(HotelsViewHolder feedViewHolder, int i)
{
feedViewHolder.hotelName.setText(d2.feeds.get(i).getName());
Picasso.with(feedViewHolder.mcontext).load(d2.feeds.get(i).getIcon()).into(feedViewHolder.hotel_logo);
}
@Override
public int getItemCount()
{
if(d2.feeds!=null)
{
return d2.feeds.size();
}
else
{
return 0;
}
}
}
Это CardView
то, что я использую:
food_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
app:cardCornerRadius="5dp"
android:layout_height="100dp"
card_view:cardUseCompatPadding="false"
android:id="@ id/cv">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@ id/logoOfHotel"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@ id/hotelName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Перепроверил многие вещи, все еще не в состоянии устранить проблему, что может быть причиной этого? Любая помощь будет высоко оценена.
Комментарии:
1. Выведите размер d2.feeds в журнале. Это может быть 0
2. Я думаю, что adapter_data имеет значение null, пока вы устанавливаете адаптер, можете ли вы проверить его один раз?
3. после вызова doGetRequest() инициализируйте адаптер и установите для адаптера значение recyclerview и попробуйте
4. @Piyush Невозможно войти в систему, :/ также пробовал с точкой останова
onBindViewHolder()
в адаптере, кажется, она даже не вызывается, есть мысли? :/5. Замените этот адаптер = новым адаптером пользовательских мест (adapter_data); adapter_data = новым ArrayList<>(); Здесь вы заполняете адаптер перед инициализацией списка.