How to change button background when button state is changed - android

Wondering how can I change my button background programmatically by setting onClickListener.
I mean that when I firstly pressed my button it changes its background image and save it even if I release finger from it. And then if i press it the second time it must change background image again. I know that I must check what background is there at the moment but can't understand how to do it.
I've tried use getBackground method but it wasn't helpful for me. I even tried to create an XML file with selector which contains three state of my button, but it worked only until the moment I release finger from button.

You could have a global variable storing the background int:
private int backgroundNumber = 0;
Then, in onClick() you could do something like this:
backgroundNumber++;
switch (backgroundNumber % numberOfBackgrounds) { // numberOfBackgrounds is a constant of how many backgrounds there are
case 1:
button.setBackgroundResource(R.drawable.background1);
break;
// Do cases for all the backgrounds
}
I think that should work.

Try like this.
You know how many states you have. Use an int variable (lest say buttonState) to save button state (ex. states 1,2,3. MAX_STATE = 3).
On click just change state and replace background depending on the current buttonState variable value.
#Click(R.id.button_action)
void onButtonActionClicked() {
buttonState = ++buttonState % BTN_STATE_MAX;
switch (buttonState){
case BTN_SAVE:
button.setBackgroundResource(R.drawable.button_save);
break;
case BTN_LOAD:
button.setBackgroundResource(R.drawable.button_load);
break;
case BTN_DELETE:
button.setBackgroundResource(R.drawable.button_delete);
break;
}
}

Related

How can I display a button in the onCreate method of an activity based on a given condition?

I want to display a button in an activity, but the text and background of the button are different if a specific condition is met by the user. How can I initialise the same button in the OnCreate method, having two different designs based on a condition?
Here Maybe this help
val btnGet = findViewById<Button>(R.id.btnGet)
if (id == 1){ //Your condition
btnGet.text = id.toString()
btnGet.visibility = View.VISIBLE //Make Sure in xml it is gone
btnGet.setTextColor(Color.parseColor("#bdbdbd"))
btnGet.setBackgroundColor(Color.parseColor("#ffffff"))
}else{
btnGet.text = id.toString()
btnGet.visibility = View.VISIBLE
btnGet.setTextColor(Color.parseColor("#FFBB86FC"))
btnGet.setBackgroundColor(Color.parseColor("#FF03DAC5"))
}
If you want the full code I will share it with you
Happy coding
1. You can change this properties in run time.
2. You can create two drawables files to set in the button background, but the text you still needing to change in runtime.
3. And you can use data binding in your xml file, using layout Data, like:
Google Link

Remove 'tile' when clicked on

I'm working on a small project where you need to guess the picture behind the tiles. Currently everything is working, but I have no idea how I can check if someone clicked a tile.
I know I can do it with a button, but I want to be able to remove a tile when someone actually presses that tile. Is there a way to check if someone pressed somewhere on the screen or something?
You need to make your tile clickable, and then add a method on click event.
Add the following to your tiles in xml.
android:clickable="true"
android:onClick="TileClicked"
Then create a method in your activity
public void TileClicked(View v)
{
int clickedID = v.getId();
// Do something to the clicked tile .. e.g.
v.setVisiblity(View.INVISIBLE);
// or filter specific tiles
if(clickedID = R.id.myTile1)
{
// do something when tile 1 clicked
}
}
Alternatively, you can add the onclick listener in code and call the method there.

Lots of if statements

I want to make some kinda dictionary,But not exactly a dictionary,
I have two text views, One for the word, The other one for the meaning.
I have two Buttons which they change an integer's number
And finally I have lots of if, For Example:
(if i==1){
txt1.setText("x");
txt2.setText("y");
}
(if i==2){
txt1.setText("n");
txt2.setText("m");
}
Q1: Its better with switch right?
Q2: Where should I put those Switch? In each Button's ClickListener ?
Q3: Can you suggest a better way to do that?
Switch is definitely a better option.
You can have a common API that will handle this logic like:
toggleText(int i){
switch(i){
case 1:
txt1.setText("x");
txt2.setText("y");
break;
case 2:
txt1.setText("n");
txt2.setText("m");
break;
}
}
Then u can call this API from ur button cick:
button.setOnClickListener(new View.OnClickListener{
#Override
onClick(){
toggleText(pass your value here)
}
});
Let me know if u need any help.
Switch is good option than if else
Make a function and put all switch conditions in it and call that function on button click

Should I use several activities for an app with several screens?

I'm new to Android and I'm building a simple application to start with. It consists of a client with three screens. In the first screen the user is prompted for an Ip to connect to a server (I use an EditText and a button). If the connection is successfully established, some data will be retrieved from the server and the client will show the data on a blank screen (I use a TextView). This would be the second screen. Then, the user could ask the server for detailed information about any data that has been retrieved from the server, which would be the third screen (I use a TextView again).
The problem is that I don't know what's the best way to go about it. I have currently one activity and one XML file containing all the components of the view (EditText, button, TextView). Until now, I've been using setVisibility(View.GONE);to hide certain components depending on the screen the user is in. (For example in the first screen I have to hide both TextViews).
One of the problems I'm facing is that when I put the phone in a horizontal position the components I had hidden show up again. I don't know if hiding views is the ideal thing to do for my purpose.
I've thought that maybe I should use more than one activity, shouldn't I?
I really appreciate any help you can give me to structure my first app.
I would definitely recommend splitting up your App into multiple Activities/Fragments. Depending on how big the logic for each screen gets you will be glad you did it later on because each Activity only has one responsibility.
Look at your mail app for example. You got your List Activity showing you all your mails and then when you select one it starts the Detail Activity showing you the content of your mail. Each Activity is only responsible for one thing which make each one easier to write and maintain.
It also simplifies your layout definitions because each one only contains the relevant parts.
Seems like this is coming up a lot. Android destroys and recreates and Activity when the configuration changes. Screen rotation is part of the orientation. In order to avoid that, the Activity is responsible for retaining state. The mechanisms given for that are the onCreate and onSaveInstanceState. In your example, you could do something like the following:
int uiPhase = 1;
#Override
void onCreate( Bundle data ) {
uiPhase = data.getInt( "uiPhase", 1 );
// inflate layout
setPhase( uiPhase );
}
// invoke the following each time your screen changes
void setPhase( int newPhase ) {
uiPhase = newPhase;
switch( uiPhase ) {
case 1: // show UI elements for first screen, hide others
break;
case 2: // show UI elements for second screen, hide others
break;
case 3: // show UI elements for third screen, hide others
break;
}
}
#Override
void onSaveInstanceState( Bundle data ) {
data.put( "uiPhase", uiPhase );
}
I didn't want to complicate the pattern above too much, but a good method for setting visibility is as follows:
phase1view.setVisibility( uiPhase == 1 ? View.VISIBLE : View.GONE );
phase2view.setVisibility( uiPhase == 2 ? View.VISIBLE : View.GONE );
phase3view.setVisibility( uiPhase == 3 ? View.VISIBLE : View.GONE );
That pulls the repetition in the setPhase method quite a bit together.
Set button visibility to GONE (button will be completely "removed" -- the buttons space will be available for another widgets) or INVISIBLE (button will became "transparent" -- its space will not be available for another widgets):
use in place of
setVisibility(View.GONE)
change to
setVisibility(View.INVISIBLE) and try

Effectivity, Android switch or click listener for each button

I cant found the topic, perhaps someone can teach me some about android effectivity when the topis is about onclicklistener for buttons.
Lets say I got 10 buttons on a page (just an example now)
What's the best thing to do?
A switch that switch id for the buttons?
A onClickListener for each button?
What method is the faster one, and why?
Is there any different at all?
Best practice is to go with 1st option: A switch that switch id for the butttons.
As per my experience, i would suggest you to assign android:onClick attribute with same value, say for example: android:onClick="btnClicker"
And now you have to implement the same method inside the activity class as:
public void btnClicker(View v)
{
switch(v.getId())
{
case R.id.btn1:
break;
case R.id.btn2:
break;
case R.id.btn3:
break;
}
}
About 2nd option:
I don't prefer it because it increase number of code lines because just think you are having 10 buttons and you assign separate click listener for each buttons. And now compare it with the above 1st option, you will realize it.
So i would suggest you to go with 1st option i have suggested with example above, main reason is it decrease number of code lines and better readability of code.
Why there is better readability in 1st option i have suggested above?
Because you know you just have to check this particular function only for the code for every buttons, because everything is here inside a function.
I would be surprised if there is any significant difference. I would go with #2 because I think it leads to clearer code.
I think answer 1 is effectivity.
because create object will slow down the app.
and the RAM limit in mobile phone should be considered.

Categories

Resources