Can any one tell me? how can i use the same button for two Action?
Like em using one button in my activity that calculate some values and after calculating the when i again press same button then reset the all fields. Like in this Application
http://www.craziness.com/games/play-love-tester/ when i test the love by pressing the button
then i again press the same button then all fields reset.
what should i use in my activity for the above problem?
You can create a global variable which indicates the state of the program and then change this value when needed. In the OnClickListener of your Button you create an if statement which checks this variable and does the needed things for the associated value.
Example:
public class MainActivity extends Activity {
private int state = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (state == 0) {
// State 1
}
else if (state == 1) {
// State 2
}
else {
// Default state
}
}
});
// Rest of your code including state changing part
}
}
You can do it by changing the button text.
If you do not want that someone sees the text change. Test (example "click" and the other state "click " (1 blank at the end) or another solution.
....
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// todo: check for expected instance (Button)
Button btc = (Button)v;
String bText = btc.getText().toString();
if (bText == "open") {
btc.setText("close");
}
else if (bText == "close") {
btc.setText("open");
}
}
[...]
You can do so by using a toggle button.
In your xml file add a toggle button
<ToggleButton
android:id="#+id/tbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textOff="Reset"
android:textOn="Calculation"
android:background="#drawable/icon"/>
Java file
public class Reviews extends Activity implements OnClickListener {
private ToggleButton tbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tbtn = (ToggleButton) findViewById(R.id.tbtn);
tbtn.setOnClickListener(this);
public void onClick(View view) {
if (tbtn.isChecked()) {
//calculate the result
}
else {
//Reset your global calculation variable;
}
}
}
}
Related
I am adding a Button to my first Wear OS application. When I follow a model from
my existing Android applications, there appears to be difference due to
"WearableActivity" versus "Activity". I cannot define the OnClickListener.
In my on create is this:
bottomButton = findViewById(R.id.bottomButton);
setListener();
later in the main activity source is this
void setListener()
{
bottomButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) // toggle between report and graph display
{ if (showGraph)
{showReport=true; showGraph=false;bottomButton.setText("show Report");}
else
{showReport=false;showGraph=true;bottomButton.setText("show Graph");}
} // end, onClick
}); // end, setOnClickListener
} // end, setListener()
In both cases the button is defined in XML and found and used as follows
OkButton = (Button) findViewById(R.id.OkButton);
OkButton.setOnClickListener(this);
it does compile anyway. And I can access the items in the button such as text. But when I change the text, it doesn't appear on the screen. And when I push the button in the emulator, it doesn't register any action.
The problem is not from your code but from the Android wear emulator. Your wear emulator is in the ambient(low power) mode. Click in the top of the emulator window to toggle between interactive(full power) and ambient modes(low power).
How can I define and use a button in the wear os application.
The same way it is done on the mobile side. Below is an example
public class MainActivity extends WearableActivity implements View.OnClickListener {
Button clickMeButton;
TextView textView;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
clickMeButton = findViewById(R.id.click_me_button);
textView = findViewById(R.id.test_textview);
clickMeButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
count++;
textView.setText("I am clicked: "+count);
}
#Override
public void onEnterAmbient(Bundle ambientDetails) {
// Handle entering ambient mode
super.onEnterAmbient(ambientDetails);
Log.e("Hello", "I'm ambient");
}
#Override
public void onExitAmbient() {
// Handle exiting ambient mode
super.onExitAmbient();
Log.e("Hello", "exit ambient");
}
#Override
public void onUpdateAmbient() {
// Update the content
super.onUpdateAmbient();
Log.e("Hello", "update ambient: " + isAmbient());
}
}
Below is the results of the above activity (NB: Click in the top of the emulator window to toggle between interactive and ambient modes):
EDIT
To avoid implementing View.OnClickListener in your activity you can pass an instance of View.OnClickListener when calling setOnClickListener for the OkButton like you are already doing for the bottomButton.
OkButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something when OkButton is clicked
}
});
I need to be able to add buttons to a layout using an "add" button. The problem is that I need each button to have an OnClickListener()/onClick method. I was thinking every time the "add" button is pressed then i would add a new button to an array but im not sure add the listener and implement an onClick method for each button I create.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SmartChronometer chrono = (SmartChronometer) findViewById(R.id.chrono);
final Button start = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (chrono.isRunning())
chrono.pause();
else {
chrono.chronoStart();
}
}
});
}
I need to add chronomoter,button and listeners every time I click an "Add" button.
set all the clicklisteners as you wich!
call findViewById(R.id.btnSecond).setVisibility(View.GONE); on creat, then when clickin the first button
Button btnSecond;
...
public void onClick(View v) {
findViewById(R.id.btnSecond).setVisibility(View.VISIBLE);
if (btnSecond.getVisibility() == View.VISIBLE); {
findViewById(R.id.btnThird).setVisibility(View.VISIBLE);}
}
this way you can put all your information in the java file and all buttons in xml, but they will be hidden until click.
This is one way, other answer my come. Good Luck :)
implements OnClickListener
Button add = (Button) findViewById (R.id.addButton);
add.setOnClickListener (this);
List<Button> buttons = new ArrayList <Button>();
for (int i = 0; i < buttons.size (); i++){
buttons.get (i).setOnClickListener (this);
}
#Override
public void onClick (View v){
for (int i = 0; i < buttons.size (); i++){
if (v.getId () == buttons.get (i).getId ()){
// do stuff you want
}else if (v.getId() == R.id.addButton){
//add button
}
}
}
Hope this will work, didnt test it.
This is the first time I'm ever dabbling in Android development so please bear with me.
My requirement is this:
I have two buttons on screen, A and B. If the user presses both buttons (order doesn't matter), I need another page to be displayed. Pressing either A or B should do nothing.
Is this possible? If so, how would I achieve this?
Thank you.
This is possible if you take a flag. (boolean)
You should set a flag in your button listeners.
public class Mtest extends Activity {
Button b1;
Button b2;
boolean flag_1 = false;
boolean flag_2 = false;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler1);
b2.setOnClickListener(myhandler2);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
flag_1 = true;
doSomething();
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
flag_2 = true;
doSomething();
}
};
}
public void doSomething(){
if(flag_1 && flag_2)
{
//DO SOMETHING
}
}
}
Create two boolean's like button1isClickedand button2isClicked,then set an onClickListener for each Button. When the the Button is clicked set the value of these two boolean's to true, then simply create an if() statement that will chekc to see if both buttons have been clicked, like this:
if(button1isClicked == true && button2isClicked == true){
//display your new page
}
How do i add toggle button that mute/unmute all in app sound preferably a video on how to do it.
public class MyActivity extends Activity {
private boolean _myAudioToggle;
onCreate(Bundle savedInstanceState) {
// ...
_myAudioToggle = false; // audio is off, set to true to default to on
setAudio(_myAudioToggle);
Button button = (Button) findViewById(R.id.yourButton); // where yourButton is in your layout XML file
button.setOnClickListener(new View.onClickListener {
#Override
onClick(View v) {
_myAudioToggle = !_myAudioToggle;
setAudio(_myAudioToggle);
}
});
// ...
}
// ...
}
Create a method called setAudio() that takes a boolean value and sets the audio :)
private void setAudio(boolean audioToggle) {
// your code to toggle the audio
}
I have actually read several answers to this but they are so different than the simple way I am implementing click responses that I am wondering if there is a way to add something simple to what I am doing to create an onLongClick responas.
Basically, all my XML code is written with statements like this:
android:onClick="onSync"
Then my Java has:
public void onSync(View v) {
...
Toast toast3=Toast.makeText(this, "Sync was pressed",Toast.LENGTH_SHORT);
toast3.show();
}
What I would like to do is have a different function that is called when the button gets a long press. Right now, a long press causes the same action as a short press.
Specifically, I would like to know how to interface to a routine such as this:
public void onSyncLong(View v) {
...
Toast toast3=Toast.makeText(this, "Long Sync was pressed",Toast.LENGTH_SHORT);
toast3.show();
}
I would certainly appreciate any help on this problem. It would be great if the reply told me what to do in the XML and in the Jave. Thanks so much.
----------------------------UPDATE------------------------
Here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.start_meters);
textLL = (TextView)findViewById(R.id.textLL);
textTimer = (TextView)findViewById(R.id.textTimer);
textTimeToLine = (TextView)findViewById(R.id.textTimeToLine);
Button button = (Button) findViewById(R.id.button_sync);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
}
And here is the button XML segment
<Button
android:id="#+id/buttonSync"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Gun/Sync"
android:onClick="onSync"
android:textSize="#dimen/font_small"
android:background="#drawable/round_button"
android:padding="3sp"
android:longClickable="true"/>
------------Final Update----------------
Here is the working code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.start_meters);
textLL = (TextView)findViewById(R.id.textLL);
textTimer = (TextView)findViewById(R.id.textTimer);
textTimeToLine = (TextView)findViewById(R.id.textTimeToLine);
Button button = (Button) findViewById(R.id.buttonSync);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
StartLine2.startTime = pTime + 1000*60*5;
return true;
}
});
}
You can't do this via XML. Instead, use:
Button button = (Button) findViewById(R.id.<your_id>);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
Make sure this code comes after setContentView() has been called.
Also, make sure that the android:longClickable property is set to true.
In your XML, the ID is set to buttonSync, while in the Java code you're using button_sync. This is the reason for your NullPointerException, as you don't have a button called button_sync.
public class GameScoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Log.v("TTT", "GameScoreFragment.OnCreateView()");
View viewScore = inflater.inflate(R.layout.gamescorelayout, container, false);
// set onLongClick listeners for both buttons
// when player long presses any of the two buttons, scores are reset
Button tempButton = (Button) viewScore.findViewById(R.id.id_button_pone_score);
tempButton.setOnLongClickListener( mLongListener );
tempButton = (Button) viewScore.findViewById(R.id.id_button_ptwo_score);
tempButton.setOnLongClickListener( mLongListener );
return viewScore;
}
// define a variable mLongListener to hold the listener code
// and then use mLongListener to set the listener
// if we don't define the variable, then we will have to write the listener code at two places (once for each button)
private View.OnLongClickListener mLongListener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View pView) {
//reset player scores
GameFragment tempGameFragment = (GameFragment) getFragmentManager().findFragmentById(R.id.id_gamefragment);
if (tempGameFragment != null)
tempGameFragment.resetPlayersScore(false);
return true;
}
};
}