I have RecycleView List with an ExpandableLinearLayout ( i use a third party library). In my ExpandableLinearLayout I have a ListView, with an custom ArrayAdapter.
I set my Adapter in the RecycleViewAdapter and submit one ArrayList that contains 4 ArrayLists and the position from the onBindViewHolder() method , too fill the different sections in the RecycleView.
I pass the data in the correct section but i get only the first element of each ArrayList. I Log some stuff and the problem is the position from the getView method in my ArrayAdapter is always 0..
I search and played around a bit but i didnt found a solution.. I hope somebody can help..
Sorry for my bad grammar
This is my RecycleView :
public class EmergencyPassAdapter extends RecyclerView.Adapter<EmergencyPassAdapter.EmergencyPassViewHolder> {
private static final String LOG_TAG = EmergencyPassAdapter.class.getName();
private Context context;
private ArrayList<CellInformation> cellInformations;
private SparseBooleanArray expandState = new SparseBooleanArray();
EmergencyPassExpandAdapter emergencyPassExpandAdapter;
public EmergencyPassAdapter(Context context, ArrayList<CellInformation> cellInformations) {
this.context = context;
this.cellInformations = cellInformations;
for (int i = 0; i < cellInformations.size(); i++) {
expandState.append(i, false);
}
}
#Override
public EmergencyPassViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_emergency_pass, parent, false);
return new EmergencyPassViewHolder(view);
}
#Override
public void onBindViewHolder(final EmergencyPassViewHolder holder, final int position) {
CellInformation cellInformation = cellInformations.get(position);
holder.imageViewIcon.setImageDrawable(cellInformation.getIcon());
holder.textViewTitle.setText(cellInformation.getTitel());
emergencyPassExpandAdapter = new EmergencyPassExpandAdapter(context, EmergencyPassExpandDetailFactory.getExpandCellInformation(context), position);
holder.listView.setAdapter(emergencyPassExpandAdapter);
if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_emergency_contacts))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_legal_guardian))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
}
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!holder.expandableLinearLayout.isExpanded()) {
Log.i(LOG_TAG, "expand");
holder.expandableLinearLayout.expand();
} else {
Log.i(LOG_TAG, "collapse");
holder.expandableLinearLayout.collapse();
}
}
});
}
#Override
public int getItemCount() {
return cellInformations.size();
}
public static class EmergencyPassViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewExpandText;
ImageView imageViewIcon, imageViewArrow;
ExpandableLinearLayout expandableLinearLayout;
RelativeLayout relativeLayout;
ListView listView;
public EmergencyPassViewHolder(View itemView) {
super(itemView);
textViewTitle = (TextView) itemView.findViewById(R.id.cell_emergency_pass_title_tv);
textViewExpandText = (TextView) itemView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
imageViewIcon = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_icon_iv);
imageViewArrow = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_arrow_icon_iv);
expandableLinearLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.cell_emergency_pass_arrow_expandable_list);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.cell_emergency_pass_root_rl);
listView = (ListView) itemView.findViewById(R.id.cell_emergency_pass_expand_lv);
}
}
}
My ArrayAdapter
public class EmergencyPassExpandAdapter extends ArrayAdapter<CellExpandInformation>{
private static final String LOG_TAG = EmergencyPassExpandAdapter.class.getName();
private ArrayList<CellExpandInformation> values;
private int checkPosition;
private Context context;
public EmergencyPassExpandAdapter(Context context, ArrayList<CellExpandInformation> values, int checkPosition) {
super(context, -1, values);
this.context = context;
this.values = values;
this.checkPosition = checkPosition;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(LOG_TAG,"View");
Log.i(LOG_TAG,"Position: " + position);
EmergencyPassExpandViewHolder viewHolder;
CellExpandInformation cellExpandInformation = values.get(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cell_emergency_pass_expand, parent, false);
viewHolder = new EmergencyPassExpandViewHolder();
viewHolder.textViewExpandTitle = (TextView) convertView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
convertView.setTag(viewHolder);
} else {
viewHolder = (EmergencyPassExpandViewHolder) convertView.getTag();
}
Log.i(LOG_TAG,"CheckPosition: " + checkPosition);
if (values != null) {
if (checkPosition == 0) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getMedications().get(position).getMedicationName());
Log.i(LOG_TAG, "Medications: " + cellExpandInformation.getMedications().get(position).getMedicationName());
} else if (checkPosition == 1) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getAllergies().get(position).getAllgergiesName());
} else if (checkPosition == 2) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getDiseases().get(position).getDiseasesName());
} else if (checkPosition == 3) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getLegalGuradian().get(position).getGuradianName());
} else if (checkPosition == 4) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getEmergencyContact().get(position).getEmergencyContactName());
}
}
for(int i = 0; i < cellExpandInformation.getMedications().size(); i++){
Log.i(LOG_TAG,"Medis: " + cellExpandInformation.getMedications().get(i).getMedicationName());
}
return convertView;
}
static class EmergencyPassExpandViewHolder {
TextView textViewExpandTitle;
ImageView imageViewPhone, imageViewEmail, imageViewAdd;
}
}
Related
I have a fragment containing a recyclerView.
When a user presses on one of their recorded exercise sets, the particular set is highlighted green.
Basically this allows them to update the weight/ reps for that particular set if they want to.
When a user then decides to press the update button, I will run a SQL query to update the weight/ reps as they entered, however I also need to deselect the selected set (recyclerView item).
I need the colour to return back to dark grey. How could this be achieved?
Fragment (Relative Code)
#Override
public void onExerciseClicked(int position) {
if (recyclerItemClicked == false) {
saveBtn.setText("Update");
clearBtn.setVisibility(View.GONE);
recyclerItemClicked = true;
double selectedWeight = adapter.getWeight(position);
String selectedWeightString = Double.toString(selectedWeight);
editTextWeight.setText(selectedWeightString);
int selectedReps = adapter.getReps(position);
String selectedRepsString = Integer.toString(selectedReps);
editTextReps.setText(selectedRepsString);
} else {
clearBtn.setVisibility(View.VISIBLE);
saveBtn.setText("Save");
recyclerItemClicked = false;
}
}
public void initRecyclerView() {
adapter = new CompletedExercisesListAdapter2(allExercises, this);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
}
Adapter
public class CompletedExercisesListAdapter2 extends RecyclerView.Adapter {
private OnExerciseClickListener onExerciseClickListener;
private List<Log_Entries> allCompletedExercises = new ArrayList<>();
public int adapterPos = -1;
public boolean isSelected = false;
public boolean swipeDetected = false;
public CompletedExercisesListAdapter2(ArrayList<Log_Entries> allCompletedExercises, OnExerciseClickListener onExerciseClickListener) {
this.allCompletedExercises = allCompletedExercises;
this.onExerciseClickListener = onExerciseClickListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == 0) {
view = layoutInflater.inflate(R.layout.new_completed_exercise_item, parent, false);
return new ViewHolderOne(view, onExerciseClickListener);
}
view = layoutInflater.inflate(R.layout.completed_exercise_item, parent, false);
return new ViewHolderTwo(view, onExerciseClickListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == 0) {
ViewHolderOne viewHolderOne = (ViewHolderOne) holder;
Log.d("adapterPos", String.valueOf(adapterPos));
Log.d("position", String.valueOf(position));
if (adapterPos == position) {
viewHolderOne.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderOne.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderOne.textViewExerciseName.setText(String.valueOf(allCompletedExercises.get(position).getChildExerciseName()));
viewHolderOne.textViewSetNumber.setText(String.valueOf(viewHolderOne.getAdapterPosition() + 1));
viewHolderOne.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderOne.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
} else if (getItemViewType(position) == 1) {
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
if (adapterPos == position) {
viewHolderTwo.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
if(adapterPos >-1 && swipeDetected == true){
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderTwo.textViewSetNumber.setText(String.valueOf(viewHolderTwo.getAdapterPosition() + 1));
viewHolderTwo.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderTwo.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
}
}
#Override
public int getItemCount() {
return allCompletedExercises.size();
}
#Override
public int getItemViewType(int position) {
// if list is sorted chronologically
if (position == 0) {
return 0;
}
if (allCompletedExercises.get(position).getChildExerciseName().equals(allCompletedExercises.get(position - 1).getChildExerciseName())) {
return 1;
} else {
return 0;
}
}
public class ViewHolderOne extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewExerciseName;
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderOne(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewExerciseName = itemView.findViewById(R.id.textView_ExerciseName3);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number56);
textViewWeight = itemView.findViewById(R.id.textView_weight78);
textViewReps = itemView.findViewById(R.id.textView_repss0);
mOnExerciseClickListener = onExerciseClickListener;
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_relative);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (isSelected) {
adapterPos = -1;
isSelected = false;
} else {
adapterPos = getAdapterPosition();
isSelected = true;
}
notifyDataSetChanged();
}
}
class ViewHolderTwo extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderTwo(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number);
textViewWeight = itemView.findViewById(R.id.textView_weight);
textViewReps = itemView.findViewById(R.id.textView_repss);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_rel);
mOnExerciseClickListener = onExerciseClickListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (!isSelected) {
adapterPos = getAdapterPosition();
isSelected = true;
} else {
adapterPos = -1;
isSelected = false;
}
notifyDataSetChanged();
}
}
public interface OnExerciseClickListener {
void onExerciseClicked(int position);
}
}
}
Create a separate method in your adapter for clearing the selection.
public void clearSelection() {
adapterPos = -1;
isSelected = false;
notifyDataSetChanged();
}
Then call adapter.clearSelection() from your update click listener.
recyclerview.onbindviewholder always in position 0
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {
public static final int UNCOMPLETED = 0;
public static final int COMPLETED = 1;
public static final int HIGHTLIGHT = 2;
public static final int HIGHTLIGHT_COMPETED = 3;
Cursor cursor;
Context context;
public NoteAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
public Cursor getCursor() {
return this.cursor;
}
public void setCursor(Cursor cursor) {
this.cursor = cursor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public int getItemViewType(int position) {
if (cursor.moveToPosition(position)) {
cursor.move(position);
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
int hightlight = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_HIGHTLIGHT));
if (completed == 1) {
if (hightlight == 1) {
return HIGHTLIGHT_COMPETED;
}
return COMPLETED;
}
if (hightlight == 1 && completed == 0) {
return HIGHTLIGHT;
}
return UNCOMPLETED;
}
return -1;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_row, parent, false);
switch (viewType) {
case UNCOMPLETED:
view = inflater.inflate(R.layout.item_row, parent, false);
break;
case COMPLETED:
view = inflater.inflate(R.layout.item_row_completed, parent, false);
break;
case HIGHTLIGHT:
view = inflater.inflate(R.layout.item_row_hightlight, parent, false);
break;
case HIGHTLIGHT_COMPETED:
view = inflater.inflate(R.layout.item_row_hightlight_completed, parent, false);
break;
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
if (!cursor.moveToPosition(position)) {
return;
}
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
Date date = Utilities.stringToDate(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_DEADLINE)));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
holder.tvContent.setText(content);
holder.tvDate.setText(Utilities.dateToString(date));
if(completed == 1){
holder.imgIcon.performClick();
}
}
#Override
public int getItemCount() {
return (cursor.getCount());
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvContent;
TextView tvDate;
ImageButton imgIcon;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
tvContent = itemView.findViewById(R.id.tvContent);
tvDate = itemView.findViewById(R.id.tvDate);
imgIcon = itemView.findViewById(R.id.imgCheck);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
cursor.move(position);
Note note = Utilities.cursorToNote(cursor);
Intent intent = new Intent(itemView.getContext(), AddNoteActivity.class);
intent.putExtras(note.sendNoteBundle());
intent.putExtra("type", true);
itemView.getContext().startActivity(intent);
}
});
}
}
}
The program does not contain any errors.
When I run the program, it always only shows the element at the 0 position, the remaining positions do not show.
function getItemCount works normally, returning 20 elements.
English is not my native language, sorry for any grammatical errors. Thanks, everyone.
Make sure the android:layout_height for your parent layout in the layout(xml) files for the various ViewHolders has been set to wrap_content instead of match_parent.
I am creating a movie app using TMDB api, Retrofit, Gson and Glide. I have two recyclerView and two layout to inflate. But I am unable to inflate 2 layout in recyclerView adapter.
I have already implemented popular and upcoming movie list in 2 different recyclerView. But they are showing using 1 single layout. I want to inflate popular movies in one layout and upcoming movies in another layout. I can't set the condition for getItemViewType() method. How can I check for popular and upcoming movies list in getItemViewType() method and implement it on onCreateViewHolder() method of recyclerView.
MovieAdapter class:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
public MovieAdapter(Context context, ArrayList<Movie> movieArrayList) {
this.context = context;
this.movieArrayList = movieArrayList;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(view);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList == null ? 0 : movieArrayList.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
private ArrayList<Movie> popularMovie, topRatedMovie;
private RecyclerView recyclerViewPopular, recyclerViewUpcoming;
private MovieAdapter movieAdapter, upcomingAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private static ViewPager mPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
String[] urls = new String[] {
"https://image.tmdb.org/t/p/w500/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg",
"https://image.tmdb.org/t/p/w500//2bXbqYdUdNVa8VIWXVfclP2ICtT.jpg",
"https://image.tmdb.org/t/p/w500//zfE0R94v1E8cuKAerbskfD3VfUt.jpg",
"https://image.tmdb.org/t/p/w500//lcq8dVxeeOqHvvgcte707K0KVx5.jpg",
"https://image.tmdb.org/t/p/w500//w9kR8qbmQ01HwnvK4alvnQ2ca0L.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initSlider();
getPopularMovies();
getUpcomingMovies();
swipeRefreshLayout = findViewById(R.id.swipe_layout);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getPopularMovies();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
}
}, 4000);
}
});
}
public void getPopularMovies() {
MovieDataService movieDataService = RetrofitInstance.getService();
Call<MovieDBResponse> callPopular = movieDataService.getPopularMovies(this.getString(R.string.apiKey));
callPopular.enqueue(new Callback<MovieDBResponse>() {
#Override
public void onResponse(Call<MovieDBResponse> call, Response<MovieDBResponse> response) {
MovieDBResponse movieDBResponse = response.body();
if(movieDBResponse!=null && movieDBResponse.getMovies()!=null) {
popularMovie = (ArrayList<Movie>) movieDBResponse.getMovies();
showOnRecyclerView();
}
}
#Override
public void onFailure(Call<MovieDBResponse> call, Throwable t) { }
});
}
public void getUpcomingMovies() {
MovieDataService movieDataService = RetrofitInstance.getService();
Call<MovieDBResponse> callUpcoming = movieDataService.getUpcomingMovies(this.getString(R.string.apiKey));
callUpcoming.enqueue(new Callback<MovieDBResponse>() {
#Override
public void onResponse(Call<MovieDBResponse> call, Response<MovieDBResponse> response) {
MovieDBResponse movieDBResponse = response.body();
if(movieDBResponse!=null && movieDBResponse.getMovies()!=null) {
topRatedMovie = (ArrayList<Movie>) movieDBResponse.getMovies();
showOnRecyclerView();
}
}
#Override
public void onFailure(Call<MovieDBResponse> call, Throwable t) { }
});
}
private void showOnRecyclerView() {
recyclerViewPopular = findViewById(R.id.rvMovies);
recyclerViewUpcoming = findViewById(R.id.rvTopMovies);
RecyclerView.LayoutManager popularLayoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager upcomingLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewUpcoming.setLayoutManager(upcomingLayoutManager);
recyclerViewPopular.setLayoutManager(popularLayoutManager);
movieAdapter = new MovieAdapter(this, popularMovie);
upcomingAdapter = new MovieAdapter(this, topRatedMovie);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 2));
}else {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerViewPopular.setItemAnimator(new DefaultItemAnimator());
recyclerViewUpcoming.setItemAnimator(new DefaultItemAnimator());
recyclerViewPopular.setAdapter(movieAdapter);
recyclerViewUpcoming.setAdapter(upcomingAdapter);
movieAdapter.notifyDataSetChanged();
upcomingAdapter.notifyDataSetChanged();
}
}
I want to inflate 2 different layout "movie_list_item.xml" and "upcoming_movie_list_item.xml" in onCreateViewHolder() method.
With in your adapter class(MovieAdapter) create a new constructor and add extra params of Int or enum whatever simple for you i am just giving you simple example:-
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
private int viewType;
public MovieAdapter(Context context, ArrayList < Movie > movieArrayList, int viewType) {
this.context = context;
this.movieArrayList = movieArrayList;
this.viewType=viewType;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == 1) {
//Popular movie layout
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
} else {
//upcoming movie layout
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
}
return new MovieViewHolder(view);
}
#Override
public int getItemViewType(int position) {
if (viewType == 1)
return 1; //Popular Movie Layout
else
return 2; //Upcoming Movie Layout
// return super.getItemViewType(position);
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList == null ? 0 : movieArrayList.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
and within your activity change on this method only
private void showOnRecyclerView() {
recyclerViewPopular = findViewById(R.id.rvMovies);
recyclerViewUpcoming = findViewById(R.id.rvTopMovies);
RecyclerView.LayoutManager popularLayoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager upcomingLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewUpcoming.setLayoutManager(upcomingLayoutManager);
recyclerViewPopular.setLayoutManager(popularLayoutManager);
movieAdapter = new MovieAdapter(this, popularMovie,1);
upcomingAdapter = new MovieAdapter(this, topRatedMovie,2);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerViewPopular.setLayoutManager(new GridLayoutManager(this, 4));
}
recyclerViewPopular.setItemAnimator(new DefaultItemAnimator());
recyclerViewUpcoming.setItemAnimator(new DefaultItemAnimator());
recyclerViewPopular.setAdapter(movieAdapter);
recyclerViewUpcoming.setAdapter(upcomingAdapter);
movieAdapter.notifyDataSetChanged();
upcomingAdapter.notifyDataSetChanged();
}
Create layout for movie_empty_item
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieViewHolder> {
private Context context;
private ArrayList<Movie> movieArrayList;
//add this two line
private static final int EMPTY_VIEW_TYPE = 0;
private static final int NORMAL_VIEW_TYPE = 1;
public MovieAdapter(Context context, ArrayList<Movie> movieArrayList) {
this.context = context;
this.movieArrayList = movieArrayList;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//return viewholder replace like this
if(viewType == NORMAL_VIEW_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_item, parent, false);
return new MovieViewHolder(view);
}else {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_empty_item, parent, false);
return new EmptyViewHolder(view);
};
}
//getItemViewType return replace like this
#Override
public int getItemViewType(int position) {
return movieArrayList.size()>0?NORMAL_VIEW_TYPE:EMPTY_VIEW_TYPE;
}
#Override
// Set values to the list item components
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.movieTitle.setText(movieArrayList.get(position).getOriginalTitle());
holder.rating.setText(String.valueOf(movieArrayList.get(position).getVoteAverage()));
String imagePath = "https://image.tmdb.org/t/p/w500" + movieArrayList.get(position).getPosterPath();
Glide.with(context)
.load(imagePath)
.placeholder(R.drawable.loading)
.into(holder.movieImage);
}
#Override
public int getItemCount() {
return movieArrayList.size() ? movieArrayList.size():1 ;
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
TextView movieTitle, rating;
ImageView movieImage;
public MovieViewHolder(#NonNull View itemView) {
super(itemView);
movieImage = itemView.findViewById(R.id.ivMovieImage);
movieTitle = itemView.findViewById(R.id.tvTitle);
rating = itemView.findViewById(R.id.tvRating);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Movie selectedMovie = movieArrayList.get(position);
Intent intent = new Intent(context, MovieActivity.class);
intent.putExtra("movie", selectedMovie);
context.startActivity(intent);
}
}
});
}
}
public class EmptyViewHolder extends RecyclerView.ViewHolder {
public EmptyViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
I want to mark radio button true in listview onItemClick so what I am doing is
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
LinearLayout item_view = (LinearLayout) view;
final RadioButton itemcheck = (RadioButton) item_view
.findViewById(R.id.listview_radiobutton);
if (itemcheck.isChecked()) {
itemcheck.setChecked(true);
} else {
itemcheck.setChecked(false);
}
itemcheck.setChecked(true);
}
My listview
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginLeft="#dimen/view_margin_15"
android:layout_marginRight="#dimen/view_margin_15"
android:layout_marginTop="#dimen/view_margin_20"
android:layout_weight="1"
android:choiceMode="singleChoice"
android:divider="#drawable/list_divider"
android:dividerHeight="#dimen/padding_2"
android:fastScrollEnabled="true"
android:footerDividersEnabled="true"
android:listSelector="#null"
android:scrollbars="none"
android:textFilterEnabled="true"
android:textStyle="normal" />
Edit:--
My Adapter code :--
public class Adapter extends ArrayAdapter<Details> {
private Context mContext;
private List<Details> transList;
private LayoutInflater infalInflater;
private OnCheckedRadioButon onCheckedRadioButon;
private Typeface mTypeface, mEditTypeface, mPasswdTypeface;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private PromoViewHolder viewHolder;
public Adapter(Context context, List<Details> mtransList, OnCheckedRadioButon onCheckedRadioButon) {
super(context, R.layout.dialog_listview, mtransList);
this.mContext = context;
this.transList = mtransList;
this.onCheckedRadioButon = onCheckedRadioButon;
this.infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try {
viewHolder = null;
row = infalInflater.inflate(R.layout.dialog_listview_code, parent, false);
viewHolder = new ViewHolder();
viewHolder.radiobutton = (RadioButton) row.findViewById(R.id.radiobutton);
viewHolder.listview_name = (TextView) row.findViewById(R.id.listview_name);
setValueText(viewHolder, position);
viewHolder.radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
onCheckedRadioButon.onCheckedButton(transList.get(position));
}
}
});
viewHolder.radiobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position != mSelectedPosition && mSelectedRB != null) {
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton) v;
}
});
if (mSelectedPosition != position) {
viewHolder.radiobutton.setChecked(false);
} else {
viewHolder.radiobutton.setChecked(true);
if (mSelectedRB != null && viewHolder.radiobutton != mSelectedRB) {
mSelectedRB = viewHolder.radiobutton;
}
}
row.setTag(viewHolder);
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
private void setValueText(ViewHolder viewHolder, final int position) {
viewHolder.listview_name.setText(transList.get(position).getName());
}
public interface OnCheckedRadioButon {
void onCheckedButton(Details pr);
}
class ViewHolder {
RadioButton radiobutton;
TextView listview_name;
}
}
It is working but if I click on another position of the listview then the previous radiobutton position is not unchecked.I want to uncheck all the previous ones and mark only one at a time.
Any help will be appreciated.
Use POJO classes (Setter or Getter) to manage this type of condition. Use boolean variable in that class and change its values according to the position true or false.
POJO Class Like :
public class CheckListSource {
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
In your adapter :
private ArrayList<CheckListSource > itemsData;
public ChildListAdapter(Activity activity, ArrayList<ChildListResponse> baseResponse) {
this.itemsData = baseResponse;
this.activity = activity;
}
In BindViewHolder Like :
viewHolder.checkParentView.setTag(itemsData.get(position));
viewHolder.checkParentView.setOnClickListener(checkedListener);
private View.OnClickListener checkedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckListSource childListResponse = (CheckListSource ) v.getTag();
if (childListResponse.isSelected())
childListResponse.setSelected(false);
else
childListResponse.setSelected(true);
notifyDataSetChanged();
}
};
Use a boolean array in your Activity. Each boolean value corresponds to a RadioButton.
If a RadioButton is checked, set its boolean value to true, and set all other boolean values in the array to false.
In the getView() of your Adapter, call your_radio_button.setChecked(your_boolean_array[position]).
Once the boolean array is modified, call your_adapter.notifyDataSetChanged().
Checkout this it works for me..
public class ProgramAdapter extends ArrayAdapter<KeyInformation> {
private final String TAG = "ProgramAdapter";
private List<KeyInformation> mList;
private Context mContext;
private LayoutInflater mInflater;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private String mUserApllication = "";
public ProgramAdapter(Context context, List<KeyInformation> objects) {
super(context, R.layout.program_item, objects);
mContext = context;
mList = objects;
mInflater = ( LayoutInflater ) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mUserApllication = Settings.System.getString(mContext.getContentResolver(),
Settings.System.PROGRAMMABLE_KEY_ACTION);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.program_item, parent, false);
holder.mImageView = (ImageView) convertView.findViewById(R.id.icon);
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mSeparator = (TextView) convertView.findViewById(R.id.title_separator);
holder.mRadioButton = (RadioButton) convertView.findViewById(R.id.radioBtn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mRadioButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false);
}
mUserApllication ="";
mSelectedPosition = position;
mSelectedRB = (RadioButton) view;
}
});
String userApp = mList.get(position).packageName;
if(mUserApllication.equals(userApp)) {
mSelectedPosition = position;
}
if (mSelectedPosition != position) {
holder.mRadioButton.setChecked(false);
} else {
holder.mRadioButton.setChecked(true);
mSelectedRB = holder.mRadioButton;
}
holder.mImageView.setImageDrawable(mList.get(position).icon);
holder.mTextView.setText(mList.get(position).lable);
if (position == 5) {
holder.mSeparator.setVisibility(View.VISIBLE);
} else {
holder.mSeparator.setVisibility(View.GONE);
}
return convertView;
}
public int getmSelectedPosition () {
return mSelectedPosition;
}
private static class ViewHolder {
ImageView mImageView;
TextView mTextView;
TextView mSeparator;
RadioButton mRadioButton;
}
}
Please go through below, it will work.
class Details{
public boolean isSelect=false;
}
public class Adapter extends ArrayAdapter<Details> {
private Context mContext;
private List<Details> transList;
private LayoutInflater infalInflater;
private OnCheckedRadioButon onCheckedRadioButon;
private Typeface mTypeface, mEditTypeface, mPasswdTypeface;
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
private PromoViewHolder viewHolder;
public Adapter(Context context, List<Details> mtransList, OnCheckedRadioButon onCheckedRadioButon) {
super(context, R.layout.dialog_listview, mtransList);
this.mContext = context;
this.transList = mtransList;
this.onCheckedRadioButon = onCheckedRadioButon;
this.infalInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateList(){
viewHolder.radiobutton.setChecked(false);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try {
viewHolder = null;
row = infalInflater.inflate(R.layout.dialog_listview_code, parent, false);
viewHolder = new ViewHolder();
viewHolder.radiobutton = (RadioButton) row.findViewById(R.id.radiobutton);
viewHolder.listview_name = (TextView) row.findViewById(R.id.listview_name);
setValueText(viewHolder, position);
viewHolder.radiobutton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
onCheckedRadioButon.onCheckedButton(transList.get(position));
}
}
});
viewHolder.radiobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Details detail=transList.get(position);
for(int i=0;i<transList.size;i++){
Detail b=transList.get(i);
b.isSelect=false;
}
detail.isSelect=true;
adapter.notifydatasetchange();
}
});
Details detail=transList.get(position);
if (detail.isSelect) {
viewHolder.radiobutton.setChecked(true);
} else {
viewHolder.radiobutton.setChecked(false);
}
row.setTag(viewHolder);
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
private void setValueText(ViewHolder viewHolder, final int position) {
viewHolder.listview_name.setText(transList.get(position).getName());
}
public interface OnCheckedRadioButon {
void onCheckedButton(PromoDetails promoDetails);
}
class ViewHolder {
RadioButton radiobutton;
TextView listview_name;
}
}
I have a simple task that is to take string input from Dialog then add it to listview with checkbox .
What happening is that , I entered test through dialog but it is not displaying after adding and also code doesn't have any error during runtime .
MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
ListView list;
MyCustomAdapter dataAdapter ;
List<SubTasksModel> subTasksModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.heading);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
subTasksModelArrayList = new ArrayList<SubTasksModel>();
list = (ListView) findViewById(R.id.list);
dataAdapter = new MyCustomAdapter(this , R.layout.child_row_add_subtask , subTasksModelArrayList);
list.setAdapter(dataAdapter);
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.add_subtask_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.et_task);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Add Subtask", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/*subTasksModelArrayList = new ArrayList<SubTasksModel>();*/
fillData(editText.getText().toString() , false);
Utility.setListViewHeightBasedOnChildren(list);
}
})
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void fillData(String s, boolean b) {
final SubTasksModel model = new SubTasksModel();
model.setTask(s);
model.setSelected(b);
subTasksModelArrayList.add(model);
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends BaseAdapter {
public List<SubTasksModel> subTasksModelList;
Context context;
private LayoutInflater mInflater;
public MyCustomAdapter(Context context, int resource, List<SubTasksModel> objects) {
this.context=context;
this.subTasksModelList=objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
LinearLayout linearLayout;
TextView task;
CheckBox cb;
}
#Override
public int getCount() {
return 0;
}
#Override
public SubTasksModel getItem(int position) {
return subTasksModelList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.child_row_add_subtask, null);
holder.task = (TextView) convertView.findViewById(R.id.tv_subtask);
holder.cb = (CheckBox) convertView.findViewById(R.id.cb_subtask);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayout01);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.task.setText(subTasksModelList.get(position).getTask());
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
subTasksModelList.get(pos).setSelected(isChecked);
}
});
/*Log.d("ArrayList"," : "+ subTasksModelList);
SubTasksModel subTasksModel = subTasksModelList.get(position);
holder.task.setText(subTasksModel.getTask());
holder.cb.setChecked(subTasksModel.isSelected());
holder.cb.setTag(subTasksModel);*/
return convertView;
}
}
SubTaskModel.java
public class SubTasksModel {
String task = "";
boolean selected = false;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
// Utility class is just to set height of listview inside scrollview.
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
Log.d("Params are : " , " : "+ params);
listView.requestLayout();
}
}
#Override
public int getCount() {
return 0;
}
replace it with
#Override
public int getCount() {
return subTasksModelList.size();
}