On scroll back radio getting uncheck - java

Here I have made a quiz app in which I use radio to select the option of question but when user scroll back most of the radio get uncheck
my adapter declear
setOption(optionA,1,pos);
setOption(optionB,2,pos);
setOption(optionC,3,pos);
setOption(optionD,4,pos);
optionA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectOption(optionA, 1, pos);
}
});
optionB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectOption(optionB, 2, pos);
}
});
optionC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectOption(optionC, 3, pos);
}
});
optionD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectOption(optionD, 4, pos);
}
});
}
private void selectOption(Button btn, int option_num, int quesId) {
if (privSelecetdB == null) {
DbQuery.g_quesList.get(quesId).setSelectedAns(option_num);
changeStatus(quesId,ANSWERED);
privSelecetdB= btn;
} else {
if(privSelecetdB.getId()==btn.getId()) {
btn.setBackground(null);
radioGroup.clearCheck();
DbQuery.g_quesList.get(quesId).setSelectedAns(-1);
changeStatus(quesId,UNANSWERED);
privSelecetdB= null;
}
else {
privSelecetdB.setBackground(null);
changeStatus(quesId,ANSWERED) ;
DbQuery.g_quesList.get(quesId).setSelectedAns(option_num);
privSelecetdB= btn;
}
}
}
private void changeStatus(int id, int status){
if(g_quesList.get(id).getStatus() != REVIEW){
g_quesList.get(id).setStatus(status);
}
}
private void setOption(RadioButton btn,int option_num,int quesId) {
if (DbQuery.g_quesList.get(quesId).getSelectedAns() == option_num) {
btn.setBackground(null);
} else {
btn.setBackground(null);
DbQuery.g_quesList.get(quesId).setSelectedAns(-1);
changeStatus(quesId,UNANSWERED);
radioGroup.clearCheck();
}
}
in the activity i use
private void setSnapHelper(){
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(QuestionView);
QuestionView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
View view = snapHelper.findSnapView(recyclerView.getLayoutManager());
quesid= recyclerView.getLayoutManager().getPosition(view);
if(g_quesList.get(quesid).getStatus() == NOT_VISITED)
g_quesList.get(quesid).setStatus(UNANSWERED);
if(g_quesList.get(quesid).getStatus() == REVIEW){
markImage.setVisibility(View.VISIBLE);
}
else{
markImage.setVisibility(View.GONE);
}
tvQuestionid.setText(String.valueOf(quesid+1)+"/" + String.valueOf(g_quesList.size()));
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
}
and declare of the database is
public static final int NOT_VISITED=0;
public static final int UNANSWERED=1;
public static final int ANSWERED=2;
public static final int REVIEW=3;
selected Ans-1,
NOT_VISITED
when the user selects the option and moves forward then it is working but when someone tries to come and change it or some of the left. The position till he move most of the option get unselected

Related

Implement search bar to filter Item and showing new activity

I am making a application which use Search bar to filter item in list view. when user search and choose an item they want, application will display activity of that item.
I try to find solution but each time user select item they want to go. the application always shows the activity of the first item. can anyone please help me how to solves this issue. below is my java code:
BottomNavigationView bottomNavigationView;
ListView listView;
FloatingActionButton share;
MaterialSearchBar timkiembar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
listView = findViewById(R.id.Lv);
listView.setSelected(true);
share = findViewById(R.id.share);
timkiembar = findViewById(R.id.timkiembar);
String[] storyname = getResources().getStringArray(R.array.stories_names);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.row,R.id.row_txt,storyname);
listView.setAdapter(adapter);
timkiembar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Reading.this, BilingualEssayDetails.class);
intent.putExtra("story_key",position);
startActivity(intent);
}
});
and below is code of BilingualEssayDetails.class:
translate = findViewById(R.id.translate);
dich = findViewById(R.id.dich);
nihon = findViewById(R.id.nihon);
paint = findViewById(R.id.paint);
layout = findViewById(R.id.layout);
txt_essay = findViewById(R.id.txt_essay);
colors= getSharedPreferences("MyColor",MODE_PRIVATE);
int colorcode= colors.getInt("color", 0);
if (colorcode!=0){
layout.setBackgroundColor(colorcode);
}
int position = getIntent().getIntExtra("story_key",0);
if (position ==0){
txt_essay.setText(""+getString(R.string.essay1));
translate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_essay.setText(""+getString(R.string.essay1_eng));
}
});
dich.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_essay.setText(""+getString(R.string.essay1_vn));
}
});
nihon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_essay.setText(""+getString(R.string.essay1));
}
});
}
if (position ==1){
txt_essay.setText(""+getString(R.string.essay2));
translate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_essay.setText(""+getString(R.string.essay1_eng));
}
});
dich.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_essay.setText(""+getString(R.string.essay2_vn));
}
});
nihon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txt_essay.setText(""+getString(R.string.essay2));
}
});
}

How to show dynamic items in one row of RecyclerView? When the row clicked shows all items again

I know how to add items to RecyclerView and show them, but let's say I add some dynamic items to the RecyclerView like this image
Here After click save button, it creates three rows in the RecyclerView like below image, which I don't want it creates three rows.
Instead I want to create one row, and when I clicked in that row then shows the three items like this image.
AddChecklist class
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
dbHelper = new DbHelper(this);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView(){
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
CheckBox checkBox = checklistView.findViewById(R.id.check_box);
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
}
else
checklistHelper.setStatus("0");
dbHelper.insertChecklist(checklistHelper.getStatus(), etChecklistItem.getText().toString(), DateTime.date(), DateTime.time(), System.currentTimeMillis());
}
finish();
break;
}
return true;
}
}
Adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
boolean isEditChecklist = false;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
checklistAdapter = new ChecklistAdapter(checks);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private boolean isEnableDelete = false;
List<ChecklistHelper> checkList;
public ChecklistAdapter(List<ChecklistHelper> checkList) {
this.checkList = checkList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.updateVisibility(isEnableDelete);
checklistChildViewHolder.checkBox.setText(checkList.get(position).getContent());
checklistChildViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String txt = checklistChildViewHolder.checkBox.getText().toString();
if (b)
checklistChildViewHolder.checkBox.setText(lineThrough(txt));
else
checklistChildViewHolder.checkBox.setText(txt);
}
});
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbHelper.deleteChecklist(id);
finish();
}
});
}
#Override
public int getItemCount() {
return checkList.size();
}
public void updateItems(boolean isEnableDelete){
this.isEnableDelete = isEnableDelete;
notifyDataSetChanged();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(this);
// long id = getIntent().getIntExtra("id", 0);
switch (item.getItemId()) {
case R.id.edit:
isEditChecklist = true;
checklistAdapter.updateItems(true);
invalidateOptionsMenu();
break;
case R.id.save:
Toast.makeText(getApplicationContext(), "saved ", Toast.LENGTH_SHORT).show();
checklistAdapter.updateItems(false);
isEditChecklist = false;
finish();
break;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Checklist");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbHelper.deleteChecklist(id);
// checklistAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "checklist deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
break;
}
return true;
}
}

how can I match seekbar to the mediaplayer?

I have a Recyclerview that each item plays media and the media has been set with an seekbar that is connected to media player I mean that each item has a seekbar too, but the problem that I am facing is that when you play the media all seekbar work at the same time as other item and sometimes when I click the first media the seekbar of last item is working not the first item after I pause media player somehow work on seekbar but every time I play a new media the seekbar of other item start working
what can i do to solve this problem ? I would be very grateful if you could do any help
public class VersionAdapter3 extends RecyclerView.Adapter<VersionAdapter3.VersionViewholder> {
Context context;
private final List<Version3> versionsList;
private final MediaPlayer mediaPlayer ;
private Integer currentlyplayingindex=-1;
Runnable run;
Handler seekHandler = new Handler();
public VersionAdapter3(Context context, List<Version3> versionsList) {
this.context = context;
this.versionsList = versionsList;
this.mediaPlayer=new MediaPlayer();
mediaPlayer.setOnCompletionListener(mediaPlayer1 -> {});
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setupMediaPlayer(){
mediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
}
private void onplaybtntapped(int newIndex){
if (newIndex !=currentlyplayingindex && currentlyplayingindex!=-1){
versionsList.get(currentlyplayingindex).setState(Version3.State.STOPPED);
notifyItemChanged(currentlyplayingindex);
mediaPlayer.stop();
}
if (newIndex == currentlyplayingindex){
if (mediaPlayer.isPlaying()){
versionsList.get(newIndex).setState(Version3.State.PAUSED);
mediaPlayer.pause();
}else {
versionsList.get(newIndex).setState(Version3.State.PLAYING);
mediaPlayer.start();
}
}else {
try {
currentlyplayingindex = newIndex;
Version3 version3 = versionsList.get(newIndex);
String datasource = version3.getSong();
version3.setState(Version3.State.PLAYING);
mediaPlayer.reset();
mediaPlayer.setDataSource(datasource);
mediaPlayer.prepare();
mediaPlayer.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
notifyItemChanged(newIndex);
}
#Override
public void onViewAttachedToWindow(#NonNull VersionViewholder holder) {
super.onViewAttachedToWindow(holder);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setupMediaPlayer();
}
}
#NonNull
#Override
public VersionViewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.raw3,parent,false);
return new VersionViewholder(view);
}
#Override
public void onBindViewHolder(#NonNull VersionViewholder holder, int position) {
Version3 version3 = versionsList.get(position);
holder.codeNameTxt.setText(version3.getCodeName());
holder.versionTxt.setText(version3.getVersion());
holder.descriptiontxt.setText(version3.getDescription());
holder.seekBar.setMax(mediaPlayer.getDuration());
holder.seekBar.setTag(position);
run = new Runnable() {
#Override
public void run() {
holder.seekBar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 100);
}
};
run.run();
holder.adjustBtnTextByState(version3.getState());
holder.btnplay.setOnClickListener(view -> onplaybtntapped(position));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
holder.btnplay.setText("play");
}
});
boolean isExpandable = versionsList.get(position).isExpandable();
holder.expandableLayout.setVisibility(isExpandable ? View.VISIBLE : View.GONE);
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mediaPlayer != null && b) {
//holder.seekBar.setProgress(i);
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public int getItemCount() {
return versionsList.size();
}
public class VersionViewholder extends RecyclerView.ViewHolder {
TextView codeNameTxt, versionTxt, descriptiontxt;
LinearLayout linearLayout;
RelativeLayout expandableLayout;
Button btnplay;
SeekBar seekBar;
public VersionViewholder(#NonNull View itemView) {
super(itemView);
seekBar=itemView.findViewById(R.id.seekbar);
codeNameTxt = itemView.findViewById(R.id.codename);
versionTxt = itemView.findViewById(R.id.version);
descriptiontxt = itemView.findViewById(R.id.description);
btnplay = itemView.findViewById(R.id.track_play);
linearLayout = itemView.findViewById(R.id.linear);
expandableLayout = itemView.findViewById(R.id.expandable);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Version3 version3 = versionsList.get(getAdapterPosition());
version3.setExpandable(!version3.isExpandable());
notifyItemChanged(getAdapterPosition());
}
});
}
#SuppressLint("SetTextI18n")
public void adjustBtnTextByState(Version3.State state){
switch (state){
case STOPPED:
btnplay.setText("play");
break;
case PLAYING:
btnplay.setText("playing");
break;
case PAUSED:
btnplay.setText("paused");
break;
}
}
}
}

How To Add Multiple Cards Of The Same CardView To A RecyclerView?

Here is a video of what I trying to do and explanation of the issue that I am having. Go to the following link below.
https://file.re/2021/09/12/2021-09-1210-43-21/
Here is the XML, Java, and Manifest Code Video. Go to the following link below.
https://file.re/2021/09/12/2021-09-1211-32-13/
Answer worked, but now I have two new problems. Here is the video link below.
https://file.re/2021/09/12/2021-09-1212-08-04/
I am creating an app that lists CardView layouts to a RecyclerView.
My app will add the CardView layout to the RecyclerView list, but it only lists one. I want it to add multiples of the same CardView when the user clicks on the button to add the card (basically cloning the CardView layout one under the other).
Here is what I have in my Button Click...
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
addFahToCelCard.add(new RecyclerItem());
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
}
}
});
I've tried putting the ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); under the MainActivity extends AppCompatActivity class just before the onCreate like this...
public class MainActivity extends AppCompatActivity {
final private ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>();
That didn't work.
If I don't keep ArrayList<RecyclerItem> addFahToCelCard = new ArrayList<>(); in the button click listener, and I add a new CardView it will add a new one behind the original one each time the button is clicked, and if I delete the card it keep popping back up until I delete them all off. How do I fix this the way I want it to behave? I hope this all makes sense.
I appreciate the help!
Here is everything in the java class..
public class MainActivity extends AppCompatActivity {
ArrayList<RecyclerItem> addFahToCelCard;
private Animation fromBottom;
private Animation toBottom;
private Boolean clicked = false;
private RecyclerView recyclerView;
private RecyclerItemAdapter recyclerItemAdapter;
private RecyclerView.LayoutManager layoutManager;
public FloatingActionButton mainConverterMenuFloatBtn;
public TextView chooseConverterLabel, ftocConverterLabelBtn, ftokConverterLabelBtn, ctofConverterLabelBtn, ctokConverterLabelBtn, ktofConverterLabelBtn, ktocConverterLabelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fromBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.from_bottom_animation);
toBottom = AnimationUtils.loadAnimation(MainActivity.this, R.anim.to_bottom_animation);
mainConverterMenuFloatBtn = findViewById(R.id.add_temp_converter_float_btn);
chooseConverterLabel = findViewById(R.id.choose_converter_label);
ftocConverterLabelBtn = findViewById(R.id.add_f_to_c_converter_label_btn);
ftokConverterLabelBtn = findViewById(R.id.add_f_to_k_converter_label_btn);
ctofConverterLabelBtn = findViewById(R.id.add_c_to_f_converter_label_btn);
ctokConverterLabelBtn = findViewById(R.id.add_c_to_k_converter_label_btn);
ktofConverterLabelBtn = findViewById(R.id.add_k_to_f_converter_label_btn);
ktocConverterLabelBtn = findViewById(R.id.add_k_to_c_converter_label_btn);
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
mainConverterMenuFloatBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainConverterMenu();
}
});
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
closeActionButton();
}
}
});
ftokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ctokConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktofConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
ktocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (clicked) {
closeActionButton();
}
}
});
}
private void addFahToCelCard() {
}
private void mainConverterMenu() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
private void setVisibility(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setVisibility(View.VISIBLE);
ftocConverterLabelBtn.setVisibility(View.VISIBLE);
ftokConverterLabelBtn.setVisibility(View.VISIBLE);
ctofConverterLabelBtn.setVisibility(View.VISIBLE);
ctokConverterLabelBtn.setVisibility(View.VISIBLE);
ktofConverterLabelBtn.setVisibility(View.VISIBLE);
ktocConverterLabelBtn.setVisibility(View.VISIBLE);
} else {
chooseConverterLabel.setVisibility(View.GONE);
ftocConverterLabelBtn.setVisibility(View.GONE);
ftokConverterLabelBtn.setVisibility(View.GONE);
ctofConverterLabelBtn.setVisibility(View.GONE);
ctokConverterLabelBtn.setVisibility(View.GONE);
ktofConverterLabelBtn.setVisibility(View.GONE);
ktocConverterLabelBtn.setVisibility(View.GONE);
}
}
private void setClickable(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.setClickable(true);
ftocConverterLabelBtn.setClickable(true);
ftokConverterLabelBtn.setClickable(true);
ctofConverterLabelBtn.setClickable(true);
ctokConverterLabelBtn.setClickable(true);
ktofConverterLabelBtn.setClickable(true);
ktocConverterLabelBtn.setClickable(true);
} else {
chooseConverterLabel.setClickable(false);
ftocConverterLabelBtn.setClickable(false);
ftokConverterLabelBtn.setClickable(false);
ctofConverterLabelBtn.setClickable(false);
ctokConverterLabelBtn.setClickable(false);
ktofConverterLabelBtn.setClickable(false);
ktocConverterLabelBtn.setClickable(false);
}
}
private void setAnimation(Boolean clicked) {
if (!clicked) {
chooseConverterLabel.startAnimation(fromBottom);
ftocConverterLabelBtn.startAnimation(fromBottom);
ftokConverterLabelBtn.startAnimation(fromBottom);
ctofConverterLabelBtn.startAnimation(fromBottom);
ctokConverterLabelBtn.startAnimation(fromBottom);
ktofConverterLabelBtn.startAnimation(fromBottom);
ktocConverterLabelBtn.startAnimation(fromBottom);
} else {
chooseConverterLabel.startAnimation(toBottom);
ftocConverterLabelBtn.startAnimation(toBottom);
ftokConverterLabelBtn.startAnimation(toBottom);
ctofConverterLabelBtn.startAnimation(toBottom);
ctokConverterLabelBtn.startAnimation(toBottom);
ktofConverterLabelBtn.startAnimation(toBottom);
ktocConverterLabelBtn.startAnimation(toBottom);
}
}
private void closeActionButton() {
setVisibility(clicked);
setClickable(clicked);
setAnimation(clicked);
clicked = !clicked;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.show_hide_float_convert_btn) {
if (mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.GONE);
item.setIcon(R.drawable.ic_baseline_visibility_off_32);
} else if (!mainConverterMenuFloatBtn.isShown()) {
mainConverterMenuFloatBtn.setVisibility(View.VISIBLE);
item.setIcon(R.drawable.ic_baseline_visibility_32);
}
} else if (id == R.id.app_help) {
} else if (id == R.id.tip_developer) {
} else if (id == R.id.premium_features) {
} else if (id == R.id.about_app) {
} else if (id == R.id.exit_app) {
}
return super.onOptionsItemSelected(item);
}
public static class RecyclerItemAdapter extends RecyclerView.Adapter<RecyclerItemAdapter.RecyclerViewHolder> {
public ArrayList<RecyclerItem> recyclerItemList;
public AdapterView.OnItemClickListener recyclerItemListener;
public interface OnItemClickListener {
void onItemClick (int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
recyclerItemListener = (AdapterView.OnItemClickListener) listener;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
EditText inputFahValueET;
TextView fahtoCelResult;
ImageView tempIconAndConvertBtn;
ImageView deleteCardBtn;
String shortResult, longResult;
public RecyclerViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
inputFahValueET = itemView.findViewById(R.id.input_fahrenheit_value_to_convert);
fahtoCelResult = itemView.findViewById(R.id.output_result_ftc);
tempIconAndConvertBtn = itemView.findViewById(R.id.temp_icon_convert_btn);
deleteCardBtn = itemView.findViewById(R.id.remove_card);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
public RecyclerItemAdapter(ArrayList<RecyclerItem> rList) {
recyclerItemList = rList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fahrenheit_to_celsius_converter_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v, (OnItemClickListener) recyclerItemListener);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
RecyclerItem currentItem = recyclerItemList.get(position);
final String[] result = new String[1];
holder.tempIconAndConvertBtn.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
String getIputFahValue = holder.inputFahValueET.getText().toString();
NumberFormat nf = new DecimalFormat("0.000");
if(!getIputFahValue.isEmpty()) {
double d = Double.parseDouble(getIputFahValue);
double dd = d - 32;
double ddd = dd * 5;
double dddd = ddd / 9;
result[0] = Double.toString(dddd);
holder.fahtoCelResult.setText(nf.format(dddd) + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = nf.format(dddd) + "°C";
holder.longResult = getIputFahValue + "°F is " + nf.format(dddd) + "°C";
if (result[0].contains(".0")) {
result[0] = result[0].replace(".0", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}else if (result[0].contains(".000")) {
result[0] = result[0].replace(".000", "");
holder.fahtoCelResult.setText(result[0] + "°C");
holder.fahtoCelResult.setVisibility(View.VISIBLE);
holder.shortResult = result[0] + "°C";
holder.longResult = getIputFahValue + "°F is " + result[0] + "°C";
}
}else {
Toast.makeText(view.getContext(), "Fahrenheit Value Field Cannot Be Blank!", Toast.LENGTH_LONG).show();
}
}
});
holder.fahtoCelResult.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder adb = new AlertDialog.Builder(view.getContext());
adb.setIcon(R.drawable.ic_baseline_file_copy_32);
adb.setTitle("Copy Result");
adb.setMessage("You can copy the result to your clipboard if you would like. Choose if you want the short or long result copied to your clipboard.\n\nExample of Short and Long Result:\nShort Result: 32°C\nLong Result: 0°F is 32°C");
adb.setPositiveButton("Short", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.shortResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNegativeButton("Long", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ClipboardManager cbm = (ClipboardManager) view.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Copy", holder.longResult);
cbm.setPrimaryClip(clip);
Toast.makeText(view.getContext(), "Result Copied!", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}});
adb.create();
adb.show();
return false;
}
});
holder.deleteCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemList.remove(position);
notifyItemRemoved(position);
}
});
}
#Override
public int getItemCount() {
return recyclerItemList.size();
}
}
public class RecyclerItem {
public RecyclerItem() {
}
}
}
The recyclerView should be listing the CardViews and also allowing duplicates.
Well, I think you are just using the RecyclerView the wrong way.
In your code snippet, you are initializing the RecyclerView as well as the adapter and all other components every time the user clicks the button.
First of all you will have to create the insert method in the RecyclerItemAdapter class.
RecyclerItemAdapter.java
class RecyclerItemAdapter extends RecyclerView.Adapter<YourViewHolder> {
private ArrayList<RecyclerItem> items;
RecyclerItemAdapter(ArrayList<RecyclerItem> recyclerItems) {
this.items = recyclerItems;
}
//...
public void addItem(RecyclerItem item) {
items.add(item);
notifyDataSetChanged();
}
}
Then, you have ton initialize the RecyclerView only once. The best place to do that is in the onCreate method.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<RecyclerItem> addFahToCelCard;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addFahToCelCard = new ArrayList<>();
setupRecyclerView();
setupClickListener();
}
private void setupRecyclerView() {
recyclerView = findViewById(R.id.recycler_item_view);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerItemAdapter);
}
}
Now add your onClickListener which will only add the card to the list.
private void setupClickListener() {
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
recyclerItemAdapter.addItem(new RecyclerItem());
}
});
}
What is your xml layout for this cardview ? It looks like this cardview is in another layout that has match parent as width and height.
If thats the case items are too big to show.
Okay so try making first reletive layout height = 100dp to match the card view in fahrenheit_to_celsius_converter_layout.xml
well I didn't understand the problem very well but from what I understood here's what you should do :
first you shouldn't be creating a new recycler view on every button click, instead you should put the code that initializes the recycler view in onCreate method that exist in the activity class and just keep a reference to the arraylist that holds the data and the adapter as global variables.
whenever the user clicks the button you should add a new item to the arraylist of data and use adapter.notifyDataItemSetChanged to tell the recycle view to check if there's any change happened to the recycle view and take action if necessary
here's a part of code that explains what I'm saying and I hope you that even if that doesn't answer your question, you catch a glimpse of how to deal with recyclerview :
first as I said you should keep a reference to the arraylist that holds the data and the adapter as global variables so put those outside any method in the activity
RecyclerItemAdapter recyclerItemAdapter ;
ArrayList <RecyclerItem>addFahToCelCard ;
and then put this code instead of the button code
addFahToCelCard = new ArrayList<>();
recyclerView = findViewById(R.id.recycler_item_view);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerItemAdapter = new RecyclerItemAdapter(addFahToCelCard);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerItemAdapter);
ftocConverterLabelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addFahToCelCard.add(new RecyclerItem());
recyclerItemAdapter.notifyDataSetChanged();
}
}
});
that way whenever you want to edit the recyclerView data anytime you can add/remove items from the global arraylist and notify the adapter just like the code inside the button OnClickListener
update to the last video posted about the exception
this problem raises when you delete some items, try to use holder.getAbsoluteAdapterPosition(), instead of getAdapterPosition or the old final position value.
whenever you use a value inside a listener I guess it takes the value that exists right now and hold it as final, so if you have 5 items and deleted the first 3, the last two will still have their position stored as 4 and 5 instead of 1 and 2, thats why you should call the holder.getAbsoluteAdapterPosition() to get the current position instead of the final stored one, that way he stores the holder as final instead of storing a const int value.

How to select a tab without triggering listener?

I have multiple tabs and let's say:
The user swipes down: it should change tabs depending on which
category it is on.
The user clicks on the tab: it should move
to the the top of the view the category is on.
My problem is when I select the tab once the user gets to a certain view, it triggers onTabSelected and slides to the top of the view.
Is there a way I could change the tab selected without triggering the Listener?
This is my code
public class Activity extends AppCompatActivity {
public TabLayout tabLayout;
public RecyclerView firstView,secondView;
public NestedScrollView nestedScrollView;
public RelativeLayout relativeLayout;
public boolean clicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meat_category);
//removed unimportant codes
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { // I removed the boolean here because I don't know where to change the value of it.
#Override
public void onTabSelected(TabLayout.Tab tab) {
if(tabLayout.getSelectedTabPosition() == 0){
nestedScrollView.scrollTo(0, firstView.getTop());
}else if(tabLayout.getSelectedTabPosition() == 1){
nestedScrollView.smoothScrollTo(0, secondView.getTop());
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY <= firstView.getBottom()){
tabLayout.getTabAt(0).select();
clicked = false;
} else if (scrollY >= secondView.getTop() && scrollY <= secondView.getBottom() ){
tabLayout.getTabAt(1).select();
clicked = false;
}
}
});
}
}
I faced the same problem and just fix it by the code below. First I declare the TabLayout.OnTabSelectedListener field in my class -
private TabLayout.OnTabSelectedListener tabSelectedListener;
tabSelectedListener = new TabLayout.OnTabSelectedListener() { // I removed the boolean here because I don't know where to change the value of it.
#Override
public void onTabSelected(TabLayout.Tab tab) {
if(tabLayout.getSelectedTabPosition() == 0){
nestedScrollView.scrollTo(0, firstView.getTop());
}else if(tabLayout.getSelectedTabPosition() == 1){
nestedScrollView.smoothScrollTo(0, secondView.getTop());
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
finally, remove the tabSelectedListener before selection and add it again after selection.
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (scrollY <= firstView.getBottom()){
/*First remove it*/
tabLayout.removeOnTabSelectedListener(tabSelectedListener);
tabLayout.getTabAt(0).select();
/*Then add it again*/
tabLayout.addOnTabSelectedListener(tabSelectedListener)
clicked = false;
} else if (scrollY >= secondView.getTop() && scrollY <= secondView.getBottom() ){
/*First remove it*/
tabLayout.removeOnTabSelectedListener(tabSelectedListener);
tabLayout.getTabAt(1).select();
/*Then add it again*/
tabLayout.addOnTabSelectedListener(tabSelectedListener)
clicked = false;
}
}
});

Categories