I just want to know how to start an Action (like starting a new Activity) after for example 3 Button clicks. So the Activity will only start if the Button has been clicked for 3 Times.
Keep a counter of the times you've clicked the Button anywhere you like, such as a global variable or if you want it to be cleaner, the Button itself. Add a listener to your button, you can simply add android:onClick="buttonClick" to the xml and then implement a method with that name like so:
public void buttonClick(View yourButton){
if(yourButton.getTag() == null){ //We have no tags, so first click :)
yourButton.setTag(1);
}
if((Integer)yourButton.getTag() == 3){
//Do whatever
}else{
//Increment the value of the tag
yourButton.setTag(((Integer)yourButton.getTag())+1);
}
}
You can maintain a counter .. Increment it after every click... Check if value equals desired value then build intent and start the activity .. Reset the counter before starting the activity.
Related
Creating a really basic Memory game using Java Swing. I created my GUI with a list of blank buttons where I set the icon property to none.
My code for some of the buttons is:
private void tbtnCard3ActionPerformed(java.awt.event.ActionEvent evt) {
tbtnCard3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Card3Logo.png")));
if(tbtnCard5.isSelected()){
score++;
lblScore.setText(""+score);
}
}
private void tbtnCard4ActionPerformed(java.awt.event.ActionEvent evt) {
tbtnCard4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Card7EWaste.png")));
if(tbtnCard7.isSelected()){
score++;
lblScore.setText(""+score);
}
}
private void tbtnCard5ActionPerformed(java.awt.event.ActionEvent evt) {
tbtnCard5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Card3Logo.png")));
if(tbtnCard3.isSelected()){
score++;
lblScore.setText(""+score);
}
}
I have about 20 toggle buttons and for example the code above works and the scores go up by 1 when a match is found. So for tbtnCard3, if tbtnCard5 is selected the score goes up by 1. Now my question is how would I make it so that if tbtnCard3 is selected but tbtnCard 5 is not selected, display "Wrong Match". Since im using if Selected I'm not too sure how to display "wrong match" when the case is false. It doesn't make sense to say else ifSelected as no parameters can be put either....
In my opinion, the OPs suggestion is not a good approach. You do not want the listener of one button to be "aware" of some other component unnecessarily. Suppose you have an 8-by-8 grid with toggle buttons. You don't want each toggle button listener to be aware of the other 63 toggle buttons.
I believe there is a much simpler (and cleaner) approach. What you want is for the toggle button listener to register and deregister the toggle when the state of the button changes. Let say, you add the toggle button to or remove from a list (most likely a custom class) where you can trigger some logic when the list size reaches two. Then, depending on the outcome of the comparison, it will count a match (and disable these two toggle buttons in the current state), or will display some message like "Try again" and then toggle the buttons to hide the image.
In pseudocode, this will look something like this:
public class ToggleListener implements ItemListener {
public void actionPerformed (ItemEvent event) {
JToggleButton button = (JToggleButton) event.getSource();
if (event.getStateChange()==ItemEvent.SELECTED) {
// TODO Add the button to your list..
} else {
// remove button
}
}
}
In your Swing application, you can create a single instance of the above listener and add it to every single toggle button. And, as you can see, this listener is only responsible to register and unregister the component associated with the triggered event.
The "List Listener" on the other hand, is responsible to trigger the comparison logic when the size of the list reaches two. So, if you click on the same toggle button over and over again, the only thing the button listener will do is add or remove the button from the list depending on the button's current state. However, once a second button is toggled to reveal its image, the list listener will trigger the comparison logic. I am not 100% sure, but I think you could use JavaFX ObservableList interface or one of its implementing classes to do this. If the ListChangeListener.Change class is not suitable to figure out the size of the list to trigger the logic, you will have to implement this on your own. Regardless, in pseudocode, you need to do something like this:
public void onListChange(Event event) {
if (list.size() == 2 && btn1.getIconName().equals(btn2.getIconName())) {
displayMatchMessage();
btn1.setEnabled(false);
btn2.setEnabled(false);
list.clear(); // you should remove matched items from list manually
} else {
displayMismatchMessage();
btn1.setSelected(false); // flip the card
btn2.setSelected(false); // flip the card
// list.clear(); // you should not need this because the setSelected should trigger the Item Listener which should remove item from list.
}
}
Doing something like this is a much cleaner implementation where the button listener have a single job to do and the "list listener" has another job to do. Neither one encroaches on the other's job.
I have a floating action button that, when clicked, an editText field opens up where the user can enter text. The text would then be taken via getText().toString() and entered into the text of a new button. I can make it so that each time the user goes through this process, a new button is created and positioned below the previously created button. The problem is, each new button is not unique. It creates a new instance of the exact same button so that every button has the exact same id. How do I generate a new, completely unique button with unique id in order to reference each button individually later on?
confirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!editTitle.getText().toString().isEmpty()) {
projectBtn = new Button(getActivity());
projectBtn.setId(R.id.projNewBtn);
projectBtn.setText(editTitle.getText().toString());
project_layout.addView(projectBtn);
}
editTitle.setText("");
project_layout.removeView(editTitle);
project_layout.removeView(linearLayout);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
}
});
I just solved my own problem by simply adding two lines of code; one to initialize a button ArrayList, and one to add the button to the array each time a new button is created. I simply set the id as a variable int so that once stored in the array, I am able to reference it via the corresponding number position.
Java Android question
I have x, say 5, buttons in a row.
Each button has a different number value displayed on the button.
Button one is active, the rest are not- not clickable. They are greyed out.
To show Button 1 is active it fades up and down.
Once clicked the button pops up a message. The user Ok's that, this activates Button 2, and deactivates Button 1.
Then it happens through all buttons, one by one. The final button doesn't produce the pop up message.
My question...
I want to create a method that sets the first button as current and then once clicked sets the next as current, and so on.
Can anyone tell me how to do this? I don't need to know how to fade buttons etc, its literally how to set button as current, and within that method the user click sets the next button as current.
Many thanks in advance.
EDIT
OK, I've had a go...its not working, but it seems so close...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_workout_one);
int[] buttonIds = new int[] {R.id.button_1,R.id.button_2,R.id.button_3,R.id.button_4,R.id.button_5};
setButton(buttonIds);
}
private void setButton(int[] buttId){
int isCurrent = 0;
while(isCurrent < 5) {
Button currentButton = (Button) findViewById(buttId[isCurrent]);
//TODO Make current button pulse
currentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.clearAnimation();
v.setBackgroundColor(0xFF00FF00);
v.setFocusable(false);
v.setFocusableInTouchMode(false);
v.setClickable(false);
setTimer();
isCurrent++;
}
});
I know that the problem is the isCurrent++ is not accessible outside the onClick method. How do I right this? Am I close or is this a major funk up and do I have to rethink?
Just use a global variable which track the current button, and check this variable to identify the current active button for determining the action in onClickListener. To fade out a button try this code snippet
button.setClickable(false);
button.setBackgroundColor(Color.parseColor("#808080"));
You need something like this:
private int activeButton = 1;
private void buttonClickHandler(){
switch(activeButton++){
case : 1
button1.setEnabled(true):
// show popup, hide/animate for button 1
break;
case : 2
button2.setEnabled(true);
// same for button 2
case : 3
// same for button 3
case : 4
// same for button 4
}
I have a DetailsActivity which has a TextView and TimeEditText for Date. User can add a date in that. There is a Button called Add Detail
I want that when a user enters a date like d-m-yy (future) then below this TimeEditText element, the activity should show a no. of WeekEditText as
Week1: WeekEditText1 (To add details for 1st week)
Week2: WeekEditText2 (To add details for 2nd week) and so on.
The total no. of week is (AddedDate - CurrentDate)/7
One of way of doing is calling another new activity on clicking Add Detail button and then showing all EditTexts on next activity while passsing AddedDate etc through Intent.
But is it possible to show EditText on same page below TimeEditText after user enters a date?
Have a Button that when clicked adds the number of EditTexts you need
public void onClick(View v)
{
// do whatever else you need here
int numWeeks =(AddedDate - CurrentDate)/7;
for (i=1; i<=numWeeks;i++)
{
EditText et = new EditText(YourActivity.this);
// add whatever here
}
}
You can add whatever kind of Layout you want before creating the EditText then add each one to that Layout. Something like that ought to work for you
You can dynamically inflate a layout or layout element such as and Edit Text.
For Example,
if(TimeEditText.getText != null)
EditText et = new EditText();
I need a button that, when pressed, enables all the other buttons, and changes the name of a label from "Off" to "On", and when pressed again, disables all the buttons and turns the switch to "off" back again, like an on/off switch. The thing is, I can "turn it" on, but I can't turn it back off.
If Swing, then perhaps you will want to place the buttons that you wish to control into an array or an ArrayList<AbstractButton>. That way the ActionListener of the control button can simply iterate through the array or the collection with a for loop, calling setEnabled(true) or false on the buttons. Consider making the controlling button be a JCheckBox or a JToggleButton.
Note, if you use a JToggleButton, then add an ItemListener to it. If you do so, there's no need to use booleans. Just check the state of the ItemEvent passed into the ItemListener's itemStateChanged method. If the getStateChanged() returns ItemEvent.SELECTED, then iterate through your JButton collection enabling all buttons. If it returns ItemEvent.DESELECTED, do the opposite.
Also note as per Byron Hawkins's comment:
You may want to consider that the ItemListener will receive events when the button is programmatically toggled, and also when the user toggles the button. The ActionListener only gets fired on input from the human user. I've often had bugs because I picked the wrong one.
If your button is pressed down and won't pop back up, chances are you have overridden a method in JToggleButton without calling super's version of it. Instead of overriding methods, create an ActionListener and use addActionListener() to attach to the button. When your listener is notified of button actions, check whether the toggle button is up or down and setEnabled() on the other buttons accordingly.
try use this simple code, use the variable as the flag
public int status = 0; //0 = on, 1=off
public void button_clicked()
{
//on button clicked
if(status == 0)
{
//logic here
status = 1;
buttonname.setText("Off");
}
//off button clicked
else if(status == 1)
{
//logic here
status = 0;
buttonname.setText("On");
}
}
you'll need a boolean to represent the state of the button.
In other words, when your button is off (your boolean variable is false), from your onClick listener, you'll call a method "turnButtonOn()" or something of that nature.
If your boolean variable is true, then you'll call a method turnButtonOff()
public void onClick() {
if(buttonOn){
turnOff();
}
else {
turnOn();
}
buttonOn = !buttonOn;
}