How to link buttons in android to perform a function? - java

The Android code consists of two parts Java and the XML. The XML code has helped display the buttons and switches, what code to write so as to get an output of On and Off from it.

Here is an example of basic code that allows a user to access the camera once a button has been pushed in an app:
Button camera = (Button) findViewById(R.id.button1);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
button1 corresponds to the android id for button in the xml script. You can then use the object that you've set the button to to set the OnClickListener. Inside of the the camera.setOnclickListener brackets is what you want to happen once the button is clicked. Public void onClick is a function that tells android to do something. I tried to put this in basic terms. If you'd like more specifics, there's really good android studio tutorial videos out there. This one is my favorite:
https://www.youtube.com/watch?v=QAbQgLGKd3Y&list=PL6gx4Cwl9DGBsvRxJJOzG4r4k_zLKrnxl

public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
}
}
or
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/self_destruct"
android:onClick="selfDestruct" />
public void selfDestruct(View view) {
// do something
}

if I understand your question you are asking how to react to user click on a button or a switch..
if so, you should create an instance of OnClickListener and implement the onClick() method..
simple example:
Button b = findViewById(R.id.btn_id);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});

Related

Significance of using ID in switch statements in onClick()

I wanted to ask what was the significance of creating a switch statement when implementing the onClickListener interface for multiple buttons. Like, we're already calling the setOnClickListener for that particular button by saying button_name.setOnClickListener()
So what's the point of specifying the id's again in the switch statement ? Why is it necessary to do so ? doesn't the point of doing button_name.setOnClickListener() mean - "do what's in here for this button" ?
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
What I'm trying to ask is, doing button2.setOnCLickListener() means - "Do what's set by this function for button2" right ? if not then what is the actual purpose/function performed by setOnClickListener() ?
Since you have set clickListeners to 3 different buttons, the method
....onClick(View v){.....
is going to get called when you click any of those 3 buttons. If you click the button1 you do not want to perform task actually assigned for button3. So to check and find out which button was pressed the switch statement is necessary.
Alternatively you could have done this:
corkyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the corky is clicked
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the play is clicked
}
});
so on and so forth...
This way you don't need a switch statement as in this case you know which button is being clicked on, AS you're setting the clickListener AND ALSO specifiying what you wanna do there itself.
It's more of a clean look, a more readable code style structure. If you have multiple widgets who need click listener, by implementing View.OnClickListener interface
and overriding onClick gives a cleaner look.
and inside onClick(View view){
- you can also use if statement but when the number of widgets is more
then it becomes messy, that's why we use switch statement to look cleaner.
}
and
btn.setOnClickListener(this)
// telling the button to pass the interface
so that overridden onClick can listen to this.
But If you don't want that or you have only one widget for click
then just use this, no need to implement and override.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

multiple click on single button while opening from one fragment to another?

I have created an application which uses the fragment, I am opening a fragment on the click of the first fragment with custom animation, meanwhile the animation is going on I am able to click the button on the first fragment and it creates 2 fragments. how can I not click on my button while moving from one fragment to another, I just don't want double click of the same button.
can anyone help me?
Try below
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setEnabled(false);
}
});
// on animation complete, enable it
// button.setEnabled(true);
You could try set android:clickable in your XML layout to determine whether a button can be clicked.
You could implement the following method into your code and call it when needed.
public void myMethod(boolean isLoading){
myButton.setEnabled(!isLoading);
}
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {view.setEnabled(false);}
});
Try using myButton.setEnabled(false) in your click callback function.
Try the below kotlin snippet
view.setOnClickListener {
val tag = "my_dialog"
val oldFragment: Fragment? = supportFragmentManager.findFragmentByTag(tag)
if(!(oldFragment?.isAdded == true)) {
val myDialogFragment = MyDialogFragment.newInstance()
myDialogFragment.show(supportFragmentManager, tag)
}
}
In case a fragment(with the tag specified) is already added to the activity then this code prevents new fragment creation and adding it to the activity.

Switching activities loses functionality

I have an app that consists of 3 Activities
MainActivity
CalculatorActivity
InformationActivity
My MainActivity has a confirm button that onClick starts the CalculatorActivity and everything is done correct and working as intended.
CalculatorActivity has 2 buttons, one calculateButton that checks something and shows a message and a learnMorebutton that starts the InformationActivity.
When I am on the
CalculatorActivity for the first time everything is fine and working.Pressing the learnMoreButton navigates me to the InformationActivity.That activity looks like this :
InformationActivity:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switchActivity();
}
});
}
public void switchActivity(){
final Intent intentObj = new Intent(this,CalculatorActivity.class);
startActivity(intentObj);
}
A goBack button that gets me back to CalculatorActivity.Going back seems to break the functionality.Although the layout is there and everything looks as it should be, pressing the buttons (calculateButton,learnMoreButton) does nothing.
CalculatorActivity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
final Button calculateButton = (Button) findViewById(R.id.calculateId);
final Button learnMoreButton = (Button) findViewById(R.id.learnMoreButtonId);
there are some more TextView and EditText that dont show up here but you get the point.Some more methods that do the calculations ,getters and setters.
This method
public void switchActivity(){
final Intent intentObj = new Intent(this,Information_activity.class);
startActivity(intentObj);
}
But I am not using onResume() , onPause() or any methods from the lifecycle apart from onCreate().
From some search that I have done I found out that I am doing something wrong with how I manage the activity lifecycle but I still can't find the solution.The dev documents didn't help me that much and a post with kinda the same problem as mine is old.
My question is, how the navigation from InformationActivity to CalculatorActivity should be done, so the functionality doesn't break when CalculatorActivity comes back to interact with the user.Which method should be called onResume()? , onRestart()? and how should it look like?
Thanks anyone who is willing to help.
P.S: As I mentioned , I have read the documents for the lifecycle of an Activity but I haven't found the solution.
instead of starting new activity everytime, finish the informationactivity.
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You are creating too much activities moving going back and forth this way. You can use either destroy the activity with finish(); or you can also go back to previous activity using onBackPressed();
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Try this out
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InformationActivity.this.finish();
}
});
}
Instead of saying where to go back, you can just finish the activity and it will automatically switch you to the previous one.
I think your activities are hierarchical thus you should be able to do the following from your main calculator activity:
Intent i = new Intent(this, InformationActivity.class);
startActivityForResult(i);
Your back button add this code:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResult(Result.OK);
finish();
}
});
You are all suggesting the same thing.Adding
Information_Activity.this.finish()
fixed the broken functionality , though you are all correct I can pick only one answer.
Thanks

Need to Navigate to next page Android Bluetooth

I am very new to Andriod Programming and this is probably very basic question.
In my Application, the first page contains just button (for simplicity) login button.
After the user clicks login button it displays the toast and then I need to navigate to new class(page B) where I want to connect to a specific health sensor.
Problem
1. I tried implementing the just the basic part with onClickListener for button and then when clicked, go to next page, where enable Bluetooth,etc. I could not get to next page
MainActivity.java :
public class MainActivity extends AppCompatActivity {
Button button;
PollingTest pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Logged In",Toast.LENGTH_SHORT).show();
pd = new PollingTest();
pd.call();
}
});
}
}
Second Page (Where wanted to Control BT). Never got to this page while testing on the tablet: -
For now just included if I could get a Toast atleast from this page: -
public class PollingTest extends Activity {
BluetoothAdapter btAdapter;
Button btn2;
protected void call() {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.pairinglistactivity);
btn2 = (Button)findViewById(R.id.pollB);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
});
}
}
Here app crashes after clicking on Login button in first page.
I have actually got some different errors with different code, I was not able to make proper Toast or turn BT on in the second page as it was trying them in static method.( very Confusing:( )
Please help me. I know this v v basic Q..
EDIT:
Sorry, this Q is already answered here: -
Moving from one activity to another Activity in Android
You don't start an activity by instantiating it like a normal Java class. So this is wrong
pd = new PollingTest();
pd.call();
you should be using an Intent
and follow the Activity Lifecycle
so you would want something like
Intent i = new Intent(MainActivity.this, PollingTest.class);
startActivity(i);
then override onCreate() in PollingTest.java and put what is in call() in there or call that method from onCreate().
Also, a Toast should use Activity Context

Creating buttons and separating there functionality android

my app have action bar on top of windows. Where are some buttons. Buttons count and there functions is changing depending on activity user are.
I want to write a class with methods addFirstButton, removeFirstButton and so on.
So i other classes i want to do this:
MyButtons myButtons = new MyButtons();
myButtons.addFirstButton();
So there is everything alright, but how to create a listener button if i want to do this ?
Normally i would do this:
Button backButton = (Button) customNav.findViewById(R.id.back);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Action_Bar_TestingActivity.this, "BACK", Toast.LENGTH_SHORT).show();
}
});
But i want that this would be in MyButtons class and method somehow would return a listener to that action.
So any ideas if this possible ?
Thanks.
If you're programming an Action Bar, then you can handle its "buttons" in onOptionsItemSelected(). For more information, see here: http://developer.android.com/guide/topics/ui/menus.html
If you are supporting Android 1.6-2.x, you can make a copy of the ActionBarCompat sample app. It will use some of the same XML flags as >=3.x ActionBar, but not all functionality is emulated. You may also consider using Action Bar Sherlock.
If you want to set and get your onClickListeners, you can. Nothing says you have to instantiate the click listener inside the button. But you'll have to do some bookkeeping. At the least, instantiate the listener outside your button array and pass it in.
Here's how I make a standalone click listener:
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
And here's where I attach it to a button (trivial example):
private void setBtnListener(
Button btn,
Button.OnClickListener onClickListener ) {
btn.setOnClickListener(onClickListener);
}
(If you want to see what this function really looks like, it's part of the Capturing Photos sample app.)
But I think you can see how you could use this function internal to MyButtons.
Or the hard way to code:
final Button backButton = null;
final LinearLayout navBar = (LinearLayout) customNav.findViewById(R.id.root);
Button addButton = (Button) customNav.findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
if (backButton == null)
{
backButton = new Button(this);
backButton.setText("Back");
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(Action_Bar_TestingActivity.this, "BACK", Toast.LENGTH_SHORT).show();
}
});
navBar.addView(backButton);
addButton.setText("Remove Back button");
}
{
navBar.removeView(backButton);
backButton = null;
addButton.setText("Add Back button");
}
}
});

Categories