How to change image of a button on click? - java

I have an array of bitmaps ArrayList<Bitmap> images = new ArrayList<>(3) and need to change the image of a ImageButton in every click, first images(0) then, after I click image(1) and finally image(2).
For this I am using myImageButton.setImageBitmap(images.get(0)) for the first image, how do I change to the next and then to the third?

You should use
int currentPos = 0;
onclick(){
currentPos = (currentPos+1)%(images.size()-1)
myImageButton.setImageBitmap(images.get(currentPos))
}

You can use
int currentPos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
myImageButton.setImageBitmap(images.get(0))
}
#Override
public void onClick(View v){
currentPos++;
if(currentPos == 2){
// if the imagebutton has the bitmap from position 2, you can do what you want
//example:
currentPos = 0;// so you have the first Bitmap you had when the user didn't click on the ImageButton
}
myImageButton.setImageBitmap(images.get(currentPos));
}

Related

Plus/Minus button with a counter but counter does not work properly

I have 2 buttons and a TextView to update the counter based on how many times the plus or minus button was pressed.
But, the issue is that: (for example) When I press the "+" button to 4 and goes down to 3 after pressing "-" button. Then, when I try to press "+"(add) button again it jumps up to 5 instead of 4. (i.e. the counter continues adding 1 from when the last time "+" button was pressed.
This is the adapter class where the ImageButtons and TextView listeners are implemented
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
//inflate layout flavor_item.xml
View view = LayoutInflater.from(context).inflate(R.layout.flavor_item, container, false);
//initialize UID views from flavor_item.xml
ImageView imageIv = view.findViewById(R.id.imageIv);
TextView flavorTv = view.findViewById(R.id.flavorTv);
TextView quantityTv = view.findViewById(R.id.quantityTv);
ImageButton minusbutton = (ImageButton) view.findViewById(R.id.minusbutton);
ImageButton plusbutton = (ImageButton) view.findViewById(R.id.plusbutton);
//getting data
DashboardFlavorModel model = modelArrayList.get(position);
String title = model.getTitle();
int image = model.getImage();
String qty = model.getQuantity();
//setting data
imageIv.setImageResource(image);
flavorTv.setText(title);
quantityTv.setText(qty);
//plusbutton listener
plusbutton.setOnClickListener(new View.OnClickListener() {
int count = Integer.parseInt(model.getQuantity());
#Override
public void onClick(View view) {
count++;
model.setQuantity(""+count);
quantityTv.setText(""+count);
}
});
//listener
minusbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(model.getQuantity());
if (i > 0) {
i--;
model.setQuantity(""+i);
quantityTv.setText(""+i);
} else{
Snackbar.make(view,"Cannot have < 0 QTY",Snackbar.LENGTH_SHORT).setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity("0");
quantityTv.setText(model.getQuantity());
}[![enter image description here][1]][1]
}).show();
}
}
});
(Note***) I tried checking the counter using getter and setter to check whether it worked and it did so I have no idea why when pressing "+" after "-" it wouldn't just +1 from the value after "-" button.
try putting
int count = Integer.parseInt(model.getQuantity());
inside onClick for plusbutton onclicklistener

Getting a view's index in a LinearLayout

So I have a LinearLayout set up in my XML file, and I dynamically add a bunch of CardViews to it through code upon startup of my activity. How can I make it so that when I click on any of the CardViews, I am able to obtain its position?
I tried setting up on an onClickListener for the LinearLayout, as well as an OnClickLIstener for each individual card, but couldn't find a way to obtain the index of the card that was clicked.
I'd really like to know where to put the onClickListener, and how to obtain the position that was clicked so that I can start a new activity based on what was clicked.
Here is my code:
private LinearLayout sLinearLayout;
private CardView[] cardViews;
private Workout[] workouts;
private ViewGroup.LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saved_workouts);
Intent intent = getIntent();
Parcelable[] parcelableArrayExtra = intent.getParcelableArrayExtra(MainActivity.EXTRA_WORKOUTS);
workouts = new Workout[parcelableArrayExtra.length];
System.arraycopy(parcelableArrayExtra, 0, workouts, 0, parcelableArrayExtra.length);
sLinearLayout = findViewById(R.id.viewList);
// Set the CardView layoutParams
params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
populateCardViews();
populateLayout();
}
//TODO: this method will populate the linear layout, filling the list.
private void populateLayout() {
for (CardView cardView : cardViews) {
sLinearLayout.addView(cardView);
}
}
//TODO: this method will fill up the CardViews array with an array of workouts.
private void populateCardViews() {
cardViews = new CardView[workouts.length];
for(int i = 0; i < workouts.length; i++) {
CardView card = new CardView(this);
card.setClickable(true);
card.setLayoutParams(params);
// Set CardView corner radius
card.setRadius(9);
// Set cardView content padding
card.setContentPadding(15, 15, 15, 15);
// Set a background color for CardView
card.setCardBackgroundColor(Color.BLUE);
// Set the CardView maximum elevation
card.setMaxCardElevation(50);
// Set CardView elevation
card.setCardElevation(25);
// Initialize a new TextView to put in CardView
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText("Workout WorkTime: " + workouts[i].getWorkTime());
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
tv.setTextColor(Color.WHITE);
card.setTag(workouts[i].getWorkTime());
card.addView(tv);
cardViews[i] = card;
}
}
I think you can setOnClickListener for each individual card. The index of clicked card is i
for (int i = 0; i < workouts.length; i++) {
...
final int finalI = i;
card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("TAG", "You click at card: " + finalI);
}
});
}
I not good to add so much layout programmatically. You can use a recycler view and an adapter to show a list of items. You can read this: https://developer.android.com/guide/topics/ui/layout/recyclerview
By the way, in your case: when you create a Cardview, just add onClickListener to it and the index of your Cardview is the index of it in Cardview list.
CardView cardView = new CardView(this);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click here
}
});
See if this works.
cardview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index = linearLayout.indexOfChild(v);
}
});

Reset Button to default background

I know that was already asked but it is outdated:
I have 2 buttons that represent 2 choices and if one is selected the background color gets changed to yellow. But if i want to change the choice i need to somehow reset the button:
I already try to set it back but some old design comes out. Can you provide me the id of the modern button style? And show me how to implement it?
int myChoice;
if (view == findViewById(R.id.choice1)){
myChoice = 1;
choice1.setBackgroundColor(getResources().getColor(R.color.highlightButton));
choice2.setBackgroundResource(android.R.drawable.btn_default);
}
else if (view == findViewById(R.id.choice2)){
myChoice = 2;
choice2.setBackgroundColor(getResources().getColor(R.color.highlightButton));
choice1.setBackgroundResource(android.R.drawable.btn_default);
}
}
Use Tags with getBackground(). This will assure you are always setting back to original.
Add following in beginning of function
if (v.getTag() == null)
v.setTag(v.getBackground());
Then instead of setBackgroundResource, use
v.setBackground(v.getTag());
Starting from here, you can store the default color of the button into a Drawable and grab the selection color (Yellow in your case) into anther Drawable, then toggle background colors of buttons with these Drawable variables
please check below demo
public class MainActivity extends AppCompatActivity {
private Drawable mDefaultButtonColor;
private Drawable mSelectedButtonColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1 = findViewById(R.id.btn1);
final Button btn2 = findViewById(R.id.btn2);
mDefaultButtonColor = (btn1.getBackground());
mSelectedButtonColor = ContextCompat.getDrawable(this, R.color.buttonSelected);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleButton(btn1, true);
toggleButton(btn2, false);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggleButton(btn1, false);
toggleButton(btn2, true);
}
});
}
private void toggleButton(Button button, boolean isSelected) {
button.setBackground(isSelected ? mSelectedButtonColor : mDefaultButtonColor);
}
}

How to make a slide show with sound with next and previous buttons control

I want to make a slideshow of numbers starting from 0 to 9 in pictures. When i click next button , show the picture of 1 and play sound as 'one' and so on.I want previous button to properly work.. like when I click previous button then go to previous pic and play sound which is related to that pic.
public class Numbers extends Activity {
int i = 1;
private ImageView iv;
Button next;
Button previous;
MediaPlayer ourSong;
private int currentImage = 0;
public int currentAudio = 0;
int[] images = { R.drawable.p1, R.drawable.p2, R.drawable.p3,
R.drawable.p4, R.drawable.p5, R.drawable.p6, R.drawable.p7,
R.drawable.p8, R.drawable.p9, R.drawable.p10};
int[] audios = { R.raw.a1, R.raw.a2, R.raw.a3, R.raw.a4, R.raw.a5,
R.raw.a6, R.raw.a7, R.raw.a8, R.raw.a9, R.raw.a10};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextpre);
iv = (ImageView) findViewById(R.id.ivn);
next = (Button) findViewById(R.id.buttonn);
previous = (Button) findViewById(R.id.buttonp);
// Just set one Click listener for the image
next.setOnClickListener(iButtonChangeImageListener);
previous.setOnClickListener(gButtonChangeImageListener);
}
View.OnClickListener iButtonChangeImageListener = new View.OnClickListener() {
public void onClick(View v) {
try {
// Increase Counter to move to next Image
currentImage++;
currentImage = currentImage % images.length;
iv.setImageResource(images[currentImage]);
ourSong = MediaPlayer.create(Numbers.this,
audios[currentAudio+1]);
ourSong.start();
currentAudio++;
} catch (Exception e) {
}
}
};
View.OnClickListener gButtonChangeImageListener = new View.OnClickListener() {
public void onClick(View v) {
try {
// Decrease Counter to move to previous Image
currentImage--;
currentImage = (currentImage + images.length) % images.length;
iv.setImageResource(images[currentImage]);
MediaPlayer.create(Numbers.this, audios[currentAudio]);
ourSong.start();
currentAudio--;
} catch (Exception e) {
}
}
};
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ourSong.release();
finish();
}
#Override
protected void onStart() {
super.onStart();
ourSong = MediaPlayer.create(Numbers.this,
audios[0]);
ourSong.start();
}
}
Hmm if you're trying to make a slide show, you might want to look into view pagers they look like this:
View pagers are highly customizable, You can add buttons and images and pretty much almost anything a fragment can hold on each screen. Not sure what your skill level is but ill tell you whats involved in getting this to work.
Create a layout with a view pager in it.
Create a class that extends the FragmentPagerAdapter
Override getItem() method in the adapter (this is where you define your different "screens"
Create a class that extends fragment for each screen you want to show your users.
Doing it this way in order to switch screens u just have to call setCurrentItem to change pages (when user clicks next or prev)
--edit--
Apparently theres also a something called an ImageSwitcher.
They look like this:
This is actually better for your case since you only want images. It looks a lot easier to implement than a view pager. This describes how to implement it: http://www.tutorialspoint.com/android/android_imageswitcher.htm

Text view if statement not working

Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);

Categories

Resources