We help IT Professionals succeed at work.

android - onbutton click create some code...

I have an android app that I am creating and I need to create code that will be raised when the user click a button...do I need to create a new .java file off the SRC folder..or can I out that in the same one as the mainactivity?
Comment
Watch Question

Dejan PažinHead of SW Development

Commented:

All you have to do is add a listener. Like this:

button.setOnClickListener(mCorkyListener);

You can implement the listener in the same file or in a new file. Here is the complete example:

http://developer.android.com/guide/topics/ui/ui-events.html

Commented:
You don't need to create a new .java file. You can do it in the same mainactivity.
I assume that your have a layout file for your activity say, mainlayout.xml where you have put your button.

public class  mainactivity extends Activity{
         protected void onCreate(Bundle savedValues) {
                 setContentView(R.layout.mainlayout);

                 Button button = (Button)findViewById(R.id.myButton);
                 button.setOnClickListener(new View.OnClickListener() {
                    @Override
                     public void onClick(View v) {
                        //Handle your click event here.
                      }
              });
       }
}

Hope it helps.
GlobaLevelProgrammer

Author

Commented:
okay so I have alot of XML in my app and you say that I can use the same .java..great...

but if I have a imagebutton1 in one XML and another imagebutton1 by the same name in another XML, how will the app be able to differentiate from the 2 imagebuttons by the same name..?
Head of SW Development
Commented:

Ids should be unique.
GlobaLevelProgrammer

Author

Commented:
Also how do I redirect the user from maim.XML to login.XML with a button click lisyener