Working With Buttons In Android
Solution 1:
The typical convention is to just switch off of the ID of the View that is clicked. For example:
View.OnClickListenerlistener=newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
switch(v.getId()) {
case R.id.SetWordsBtn:
startWords();
break;
case R.id.DelWordsBtn:
deleteWords();
break;
}
}
};
int[] ids = { R.id.SetWordsBtn, R.id.DelWordsBtn };
for(int i : ids) ((Button)findViewById(i)).setOnClickListener(listener);
Solution 2:
You can alternatively set up anonymous inner class(es) that listen, instead of having your Activity itself be the listener that implements OnClickListener. Example from the Android Button javadoc:
button.setOnClickListener(newView.OnClickListener() {
publicvoidonClick(View v) {
// Perform action on click
}
});
http://developer.android.com/reference/android/widget/Button.html
P.S. start your local variable names, and method names, with lower case letters -- upper case is for class names.
Solution 3:
Where you suggested:
public void onClick(View setWordsView) {
startWords();
}
public void onClick(View delWordsView) {
deleteWords();
}
If you think about it, there is no difference in the two method declarations and you would get a build error (method signatures are the same, even though the method parameter, View, has a different name).
If I understand your question correctly then the answer given by kcoppock is correct. You also could define an Anonymous Class
Solution 4:
Drag and drop button on graghiclayout.xml ...>right click the button -->choose other properties....>choose inherited from view ---->click on click ....name it callme.
That will be shows like this:
xml file
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="76dp"
android:layout_y="58dp"
android:onClick="callme"
android:text="Button" />
Run once your project:
Open src --->activity .java ----->, do the coding like this:
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but=(Button)findViewById(R.id.button1);
}
publicvoidcallme(View v)
{
//Do somthing
}
Post a Comment for "Working With Buttons In Android"