Hii i'm making an app where i have small heart image onclick of that image i've set an onclick listener so when i click on that image it is replaced by another red coloured heart image.
so my problem is when i again click on red heart image it doesnt turn to its normal state which is blank heart vector image as i'm new in android i dont have much knowledge please if someone can guide.
my code for image onclick
#Override
public void onBindViewHolder(FeedViewHolder holder, int position) {
int image_id = images[position];
//holder.background_image_layout.setImageDrawable(null);
//holder.background_image_layout.setImageResource(image_id);
holder.background_image.setBackgroundResource(image_id);
}
#Override
public int getItemCount() {
return images.length;
}
public static class FeedViewHolder extends RecyclerView.ViewHolder {
CustomTextViewMedium first_text,second_text,third_text,fourth_text,fifth_text,sixth_text,
seventh_text;
ImageView favourite_image;
CardView primary_card;
LinearLayout background_image;
ImageView background_image_layout;
CircleImageView profile_image;
public FeedViewHolder(View itemView) {
super(itemView);
background_image = (LinearLayout)itemView.findViewById(R.id.background_image);
primary_card = (CardView)itemView.findViewById(R.id.primary_card);
first_text = (CustomTextViewMedium)itemView.findViewById(R.id.first_text);
second_text = (CustomTextViewMedium)itemView.findViewById(R.id.second_text);
third_text = (CustomTextViewMedium)itemView.findViewById(R.id.third_text);
fourth_text = (CustomTextViewMedium)itemView.findViewById(R.id.fourth_text);
fifth_text = (CustomTextViewMedium)itemView.findViewById(R.id.fifth_text);
sixth_text = (CustomTextViewMedium)itemView.findViewById(R.id.sixth_text);
seventh_text = (CustomTextViewMedium)itemView.findViewById(R.id.seventh_text);
favourite_image = (ImageView)itemView.findViewById(R.id.favourite_image);
background_image_layout = (ImageView) itemView.findViewById(R.id.background_image_layout);
profile_image = (CircleImageView)itemView.findViewById(R.id.profile_image);
favourite_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(favourite_image.isPressed()){
favourite_image.setImageResource(R.drawable.ic_heart);
favourite_image.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else {
favourite_image.setImageResource(R.drawable.ic_favorite_border_black_24dp);
favourite_image.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
}
});
}
}
Use if condition like this :-
first globally define like this :-
boolean imageChange = true;
then do this in setOnClickListener like this :-
favourite_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageChange ){
favourite_image.setImageResource(R.drawable.ic_heart);
favourite_image.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageChange = false;
}else {
favourite_image.setImageResource(R.drawable.ic_favorite_border_black_24dp);
favourite_image.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageChange = true;
}
}
});
Problem is that favourite_image.isPressed() is not persistent state of the View. It will be true only while user holds its finger on the view.
To overcome this you have two similar options:
Option #1
Instead of checking isPressed you can check some other state, for example isSelected. Since this is ImageView you probably need to set the state manually on click.
public void onClick(View v) {
if(favourite_image.isSelected()){
favourite_image.setImageResource(R.drawable.ic_heart);
favourite_image.setScaleType(ImageView.ScaleType.CENTER_CROP);
favourite_image.setSelected(false)
}
else {
favourite_image.setImageResource(R.drawable.ic_favorite_border_black_24dp);
favourite_image.setScaleType(ImageView.ScaleType.CENTER_CROP);
favourite_image.setSelected(true)
}
}
Options #2
Use some simple boolean to keep track of the selected state, and set/chec its values similarity to above code.
Related
I am working on a Quiz app. First when a user opens the app they go to the MainActivity, from there when they press start they go to the Categories Activity , from there after selecting a category they go to the Sets Activity, from there after selecting a set the go to the Questions Activity and finally after completing all the questions they reach the Score Activity. Here in the score activity when the click on Done button they are redirected to the MainActivity. In the Score Activity i want to change the color of the Set that they completed to green instead of the default color. How can i do this? I created a sets item layout xml file and used an adapter to fill the gridview in the Sets Activity with views from the adapter. Currently i am getting a null object reference after clicking the Done button in the ScoreActivity.
Here is the code :
SetsAdapter.java
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return numOfSets;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View view;
if(convertView == null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
}
else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent questionIntent = new Intent(parent.getContext(), QuestionActivity.class);
questionIntent.putExtra("SETNUM", position +1);
parent.getContext().startActivity(questionIntent);
}
});
((TextView) view.findViewById(R.id.setNumber)).setText(String.valueOf(position+1));
return view;
}
}
SetsActivity.java
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
private FirebaseFirestore firestore;
public static int categoryID;
private Dialog loadingDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
Toolbar toolbar = (Toolbar)findViewById(R.id.set_toolbar);
setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
categoryID = getIntent().getIntExtra("CATEGORY_ID",1);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridView);
loadingDialog = new Dialog(SetsActivity.this);
loadingDialog.setContentView(R.layout.loading_progressbar);
loadingDialog.setCancelable(false);
loadingDialog.getWindow().setBackgroundDrawableResource(R.drawable.progress_background);
loadingDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
loadingDialog.show();
firestore = FirebaseFirestore.getInstance();
loadSets();
}
private void loadSets() {
firestore.collection("Quiz").document("CAT" + String.valueOf(categoryID))
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
long sets = (long) doc.get("SETS");
SetsAdapter adapter = new SetsAdapter(Integer.valueOf((int)sets));
sets_grid.setAdapter(adapter);
} else {
Toast.makeText(SetsActivity.this, "No Sets Exists!", Toast.LENGTH_SHORT).show();
finish();
}
} else {
Toast.makeText(SetsActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
loadingDialog.cancel();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
ScoreActivity.java
public class ScoreActivity extends AppCompatActivity {
private TextView score;
private Button done;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
score = findViewById(R.id.score_tv);
done = findViewById(R.id.score_activity_done);
String score_str = getIntent().getStringExtra("SCORE");
final int setNum = getIntent().getIntExtra("SetNum", 1);
score.setText(score_str);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
View view = findViewById(R.id.setNumber);
view.setBackgroundColor(Color.GREEN);
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
}
}
As your activity Sequence is MainActivity -> Categories -> Sets -> Scores.
You've two options to change the color with two different life cycle of the change.
To change the color on a temporary basis, this will reset itself after closing the app or resrtating the 'Sets' activity. It can be done in two ways: Using Public Static Variable and using a public function.
To change the color on a permanent basis until the app is uninstalled/reinstalled. You should use SharedPreferences. SharedPreferences acts like a private data stored in device's memory for further use and it stays there unchanged until and unless the app is removed/data is cleared. Although, apps with root permission can access any app's SharedPreferences data and can modify it as well.You can use SharedPreferences as explained here. Or, you can use some library to access it an easy way. The way I use it in all my apps is TinyDB(it's just a java/kotlin file). This works as:
//store the value from ScoreActivity after completion as
TinyDB tinyDB = TinyDB(this);
tinyDB.putBoolean("isSet1Completed",true);
//access the boolean variable in SetsActivity to change the color of any set that
//is completed and if it's true, just change the color.
TinyDB tinyDB = TinyDB(this);
Boolean bool1 = tinyDB.getBoolean("isSet1Completed");
But, it's your choice what way you want to prefer.
Now, this was about the lifecycle of the change you'll do: Temp or Permanent. Now, we'll talk about how you change the color.
Using public static variable in Sets activity. What you can do is you can set the imageView/textview whose background you want to change as public static variable. Remember, this idea is not preferred as it causes memory leak but it's just easy.
Declare it as public static ImageView imageview;(or TextView) intialize it in the
onCreated() as imageView = finViewById(R.id.viewId); in Sets activity. Call
it as new SetsActivity().imageView.setBackgroundColor(yourColor); in ScoreActivity.
Second way is to create a public function in SetsAcitvity, putting the color change code in it, and then calling it from the ScoreActivity. Just declare it as public void changeColor(){ //your work} and call it from ScoreActivity as new SetsActivity().changeCOlor(). You can also pass some arguments to the function like setId.
I've provided you every thing you need. Rest you should figure out yourself to actually learn it and not copy it.
I think simply you add flag in MainActivity.
for example, add flag in MainActivity.
boolean isFromDone = false;
and when done clicked,
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here is the issue I am facing
Intent mainIntent = new Intent(ScoreActivity.this, MainActivity.class);
mainIntent.putExtra("FromDone", true);
startActivity(mainIntent);
ScoreActivity.this.finish();
}
});
and in MainActivity, add this.
#Override
protected void onResume() {
super.onResume();
isFromDone = getIntent().getBooleanExtra("FromDone", false);
if(isFromDone) {
(TextView) view.findViewById(R.id.setNumber)).setBackgroundColor(Color.GREEN);
}
}
Suppose you have a Linear Layout in Activity A and you want to change it's background color from a button click which is present in Activity B.
Step 1 Create a class and declare a static variable.
class Util { private static LinearLayout mylayout ; }
Step 2
In the activity which is holding this layout, initialize it.
Util.mylayout = findviewbyid(R.id.linear);
Step 3Change the background color on button click from Activity B
onClick{
Util.mylayout.setBackgroundColor(Color.RED);
}
In my Android app, I have category titles shown in picture. When I click the title below content will be changed depending upon the category title. At that same time title, the background color should change but other title background colors should remain the same. How to do that in Android Studio using Java?
You can change the background colors of your TextViews like this:
yourTextViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yourContentTextView.setBackgroundColor(getResources()
.getColor(R.color.yourColor));
}
});
For every view, there is a setBackgroundColor method
yourView.setBackgroundColor(Color.parseColor("#ffffff"));
Try like below:
...
title1, title2, title3, selectedTitle;
...
title1.setOnClickListener(v -> {
updateTitleBackground(title1);
});
title2.setOnClickListener(v -> {
updateTitleBackground(title2);
});
title3.setOnClickListener(v -> {
updateTitleBackground(title3);
});
...
private void updateTitleBackground(title) {
if(selectedTitle != null) {
selectedTitle.setBackgroundColor(Color.WHITE);
}
selectedTitle = title;
title.setBackgroundColor(Color.RED);
}
...
Here are instruction and code for you to complete your target -
String titleContent1 = "Content 1", titleContent2 = "Content 2", titleContent3 = "Content 3";
textView1.setOnClickListener(v -> {
changeBackgroundColorAndTitle(titleContent1, getResources().getColor(R.color.red));
});
textView2.setOnClickListener(v -> {
changeBackgroundColorAndTitle(titleContent2, getResources().getColor(R.color.green));
});
textView3.setOnClickListener(v -> {
changeBackgroundColorAndTitle(titleContent3, getResources().getColor(R.color.white));
});
private void changeBackgroundColorAndTitle(String titleContent, int color) {
selectedTitle = title;
contentTextView.setBackgroundColor(color);
}
Try like this
// initialize your views inside your onCreate()
title1 = findViewById("yourtextviewid");
title2 = findViewById("yourtextviewid");
title3 = findViewById("yourtextviewid");
title1.setOnClickListener(this);
title2.setOnClickListener(this);
title3.setOnClickListener(this);
In your onClick method
#Override
public void onClick(View view) {
if(view == title1)
// here i assumed yourContentView and contenTextview you should use yours.
yourContentView.setBackgroundColor(Color.RED);
contentTextView.setText("Title1");
}else if(view == title2){
yourContentView.setBackgroundColor(Color.GREEN);
contentTextView.setText("Title2");
}else if(view == title3){
yourContentView.setBackgroundColor(Color.BLACK);
contentTextView.setText("Title3");
}
``
I have the following which lets the user click on an image and it turns the image invisible:
holder.redView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManualPlayingChange.notToPlaying(view);
}
});
public static void notToPlaying(View a) {
if(a.isShown()) {
a.setVisibility(View.INVISIBLE);
// b.setVisibility(View.VISIBLE);
}
}
What I want to do, is pass through another View, so that a different Ciew also changes on the same click.
The views I have:
public ViewHolder(View p) {
super(p);
playerView = p.findViewById(R.id.aPlayerInTheList);
greenView = p.findViewById(R.id.isPlaying);
amberView = p.findViewById(R.id.mightBePlaying);
redView = p.findViewById(R.id.notPlaying);
}
So I just want to be able to cycle through the 3 images.
You can just pass the holder (i.e ViewHolder) itself in notToPlaying() method instead of single view and then access all the views like:
public static void notToPlaying(ViewHolder holder){
// now you can access all the views
holder.playerView.setVisibility(View.VISIBLE);
holder.redView.setVisibility(View.GONE); // and so on.
}
Got a list (recyclerview) that should show an image for certain types of Class X, everything is working perfectly, the thing is that after I start another activity and finish to go back to it, all of the images are removed, except for the ones that don't have a type 1 after them, so it seems there is a reason that causes if type 1 doesn't make its image only gone, but all the previous
private class XHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mImageView;
private X mX;
private XHolder(View v) {
super(v);
v.setOnClickListener(this);
mImageView = (ImageView) v.findViewById(R.id.imageview);
}
public void bindX(X x){
mX = x;
if(mX.getType() == 1) {
mImageView.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
xClickEvent(mX);
}
}
Add else condition too, like:
if (mX.getType() == 1) {
mImageView.setVisibility(View.GONE);
} else {
mImageView.setVisibility(View.VISIBLE);
}
RecyclerView does not inflate your View every time, it rather uses the View going out of the screen in the onBindViewHolder() for the next item to appear. So you need to handle if and else condition both each time.
I am making use of recycler view. I have a layout that is highlighted in light red,this layout is included for each item in the recycler view. The light red layout is placed over the background image. I am using setTag method to identify the clicks of the buttons in red layout. That is working properly when i click i get the position. The problem is i want to change the image at specific position.
For example : Consider the heart button. I have set a tag on it like this.
heartButton = findViewById(id);
heartButton.setTag(position);
now i get the position by using the getTag method. But now i want to change the image of the heartButton at the a specific position. Is there something like
heartButton.getTag(position).setImageResouce(drawable);
If not how do i do this then.
use setBackgroundResource(R.drawable.XXX)
http://developer.android.com/reference/android/view/View.html#setBackgroundResource(int)
Proper way to do this is,
You have to keep the state of the heart button stored in the model(POJO) which is passed to custom adapter.
e.g.
class ModelListItem{
public static final int HEART=1,BROKEN_HEART=2;
int heartButtonState;
}
Now in onClick() of heart button, get that object from adapter using position,cosidering you have already figured it out on how to preserve position from heart button
ModelListItem item = (ModelListItem)adapter.getItem(position)
Change the state of heart button;
item.setHeartButtonState(ModelListItem.BROKEN_HEART);
adapter.notifyDatasetChanged();
You already know below explaination but just in case
To work this properly,in your getView methode of adapter you need to put the check on heartButtonState(); and use appropriate image resource.
getView(BOILERPLATE){
BOILERPLATE
switch(item.getheartButtonState()){
case ModelItemList.HEART:
heartbutton.setImageResource(heart_image);
break;
case ModelItemList.BROKEN_HEART:
heartbutton.setImageResource(broken_heart_image);
break;
}
I made a custom click listener and updated the like in the setter getter.But this works only when the view has been moved out of the view (i think it is the scrapeview)
The Setter Getter Class
public class DemoData {
int background;
boolean liked;
public DemoData(int background) {
this.background = background;
}
public int getBackground() {
return background;
}
// public void setBackground(int background) {
// this.background = background;
// }
public boolean isLiked() {
return liked;
}
public void setLiked(boolean liked) {
this.liked = liked;
}
}
The onBindViewHolder function of the recycler view
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
background = (ImageView) holder.view.findViewById(R.id.image);
layout = (LinearLayout) holder.view.findViewById(R.id.layout);
delete = (ImageView) layout.findViewById(R.id.delete);
lock = (ImageView) layout.findViewById(R.id.lock);
delete.setTag("delete_"+position);
lock.setTag("lock_"+position);
if(Constants.demoDatas.get(position).isLiked()){
delete.setImageResource(R.drawable.ic_launcher);
}
else{
delete.setImageResource(android.R.drawable.ic_delete);
}
delete.setOnClickListener(new CustomClickListener(position));
lock.setOnClickListener(new CustomClickListener(position));
}
The custom click listener is as below
public class CustomClickListener implements View.OnClickListener {
int position;
public CustomClickListener(int position) {
this.position = position;
}
#Override
public void onClick(View v) {
String tag = (String) v.getTag();
String identifier[] = tag.split("_");
// this line saves my state in the Setter Getter Class
Constants.demoDatas.get(position).setLiked(true);
}
}