I have created a button in my Android application & I tried to set onclick listner to run onClick method like follows
...
Button btn_ok;
btn_ok = (Button)findViewById(R.id.button1);
btn_ok.setOnClickListener(this);
}
public void onClick() {
EditText uN = (EditText) findViewById(R.id.EditText04);
uN.setText("Clicked!");
}
But Eclipse shows an error & says that "setOnClickListener" need to Cast Argument. After casting it is like this
btn_ok.setOnClickListener((OnClickListener) this);
Then when I'm running the program Emulator says that "Program has stopped unexpectedly"...
How can I solve this problem ?
Make sure that your class implements View.OnClickListener. You can`t just add onClick method, you must implement interface
The signature of your onClick method is wrong, which leads me to believe you're not actually implementing the interface View.OnClickListener.
The signature should be:
public void onClick(View v)
{
//your implementation, v is your button that was clicked
}
Note that the View that was clicked is passed in as an argument, so there's no need to call findViewById from inside your onClick method.
implement the onClickListener from your activity and override the method:
#override
public void onClick(View v)
{
switch(v.getId()){
case R.id.button1:
EditText uN = (EditText) findViewById(R.id.EditText04);
uN.setText("Clicked!");
break;
case default:
break;
}
}
Hope it helps.
setOnClickListener take an OnClickListener instance as parameter and OnClickListener is an interface which content an onClick() method and you are passing here setOnClickListener(this); current context. so you have two option either implements OnClickListener in your activity and second use this way :
this.btn_ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do your work here
}
});
Make sure that you are implementing the interface View.OnClickListener and also pass View to onClick method
Related
I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
tv.setText(months[rand.nextInt(12)]);
tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
}
});
It works like this. View.OnClickListenere is defined -
public interface OnClickListener {
void onClick(View v);
}
As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:
public class MyListener implements View.OnClickListener {
#Override
public void onClick (View v) {
// your code here;
}
}
But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.
setOnClickListener takes View.OnClickListener as its parameter.
This is the best way to implement Onclicklistener for many buttons in a row
implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
That what manual says about setOnClickListener method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view
is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
I need to define a layout for multiple activities in android and from the UI part, it is successful. But to code those elements to perform on each click listeners, I need to define it in all the java pages I use.
Can we globally define this in a java page and include it in the required pages?
menuButton = findViewById(R.id.menuButton);
menuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), MenuActivity.class);
startActivity(i);
finish();
overridePendingTransition(0, 0);
}
});
Yes and No.
You can create a BaseActivity which has the common logic that has to be executed for each button click.
But you need to implement the listener for the button on specific activity, since life cycle of each activity is independent of other activity.
To make the code readable better (avoiding implementing listener/setOnclickListener), you can use ButterKinfe, and create a method for OnClick() annotation, and call the method in BaseActivity.
What you essentially want to do is call the findViewById(), which can only be called if you have a reference to a Context variable. You should use your Activity Context, hence you pass this to the static function, which can then access all methods accessible via Context .
public class ExampleActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MenuUtils.setListener(this);
}
}
Define the static class like this:
public static class MenuUtils{
public static void setListener(Context context){
menuButton = context.findViewById(R.id.menuButton);
menuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do stuff
}
});
}
}
What you should be careful about is that any Activity you pass to this function should have a menuButton in it's layout, otherwise you run the risk of getting a NullPointerException, which is when findViewById() cannot find menuButton.
I don't want to allow the user to be able to click on the various images (which have onClick="mark") and call the method mark().
Method mark:
public void mark(View view){
ImageView counter = (ImageView) view;
counter.setTranslationY(-1000f);
sett(view);
}
Instead I want only method retro() to be accessible when it is called.
Method retro:
public void retro(View v){
Button bq = (Button) findViewById(R.id.b1) ;
bq.setVisibility(Button.VISIBLE);
bq.animate().alpha(1f).setDuration(2000);
//restart(bq);
}
So what should I add to retro() in order to disable mark()
So you know which View is calling the method. It's like implementing the OnClickListener for you activity, the method created is onClick(View v) (or arg0 depending on your Eclipse), defining it from xml is just specifying a sort of listener for the View, and the method from the listener as that argument.
Once you're in the method, you can do a switch for the id of the button, to perform different actions:
public void myOnClickMethod(View v)
{
switch(v.getId())
{
case R.id.button1:
//Do something for button 1
break;
case R.id.button2:
//Do something for button 2
break;
}
}
In short. Android just implements the OnClickListener for you when you define the android:onClick="myOnClickMethod" attribute.
I'm trying to make a method that is activated when another method gives it an int, and at the same time, the method can also be activated by a view.
Here is the top line of the method and where in Java the method is called:
checkNum(theNumber, null);
public void checkNum (int num, View view){
I tried using "onClick" in the xml for a button, but checkNum did not appear as a suggestion and the app crashed when I ran it. How can I fix this?
Thanks so much!
When using the onClick attribute in XML, the correct signature to use is
public void checkNum (View view)
If you want to pass in a other parameters, I suggest that you set it in Java code.
Add a click listener to your button this way:
Button button = (Button) findViewById(R.id.your_button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something when the button is clicked
}
});
I have a good background in C, and now I am writing code for android/java.
What I fail to understand that why function definition of a handler function is done inside another function. Code becomes so messy and hard to maintain and understand( from a C programmer POV).
So I have this code
final Button btnOpenPopup = (Button)findViewById(R.id.menuButton);
btnOpenPopup.setOnClickListener(new
Button.OnClickListener()
{...}
Is it possible to have a function
myButtonClickListner() {} defined in the class and btnOpenPopup.setOnClickListener((SomeCast)myButtonClickListner
I think there has to be a way, But I am not able to find it..
Please comment.
Well, there are two ways to do this:
1- Have the containing class implement the OnClickListener interface. For example:
public class MainActivity extends Activity implements OnClickListener{
//...
public void onCreate(Bundle savedState){
//...
final Button btnOpenPopup = (Button)findViewById(R.id.menuButton);
btnOpenPopup.setOnClickListener(this);
}
public void onClick(View v){
switch(v.getId()){
case R.id.button1:
//
break;
}
}
2- The second method is the one described by Selvin in his comment: creating a separate class, which implements the OnClickListener interface, and instantiate it in your onCreate(). So, assuming that you have a myButtonListener class in its own myButtonListener.java file, you can simply do:
final Button btnOpenPopup = (Button)findViewById(R.id.menuButton);
btnOpenPopup.setOnClickListener(new myButtonListener);
The idea behind using
final Button btnOpenPopup = (Button)findViewById(R.id.menuButton);
btnOpenPopup.setOnClickListener(new
Button.OnClickListener()
{...}
such coding style is that the object and its implementation stays together at one place.
in above code we have used anonymous innerclass.
If you are not comfortable with such implementation then there is also another way of doing this.
In your activity, implement onClickListener like below:
public class MainActivity extends Activity implements OnClickListener{
Button btnOk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find id of your button
btnOk = (Button) findViewById(R.id.btnOk);
//Registering it for click listener
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnOk:
System.out.println("OK button is clicked");
break;
case 2:
//some other controls
break;
default:
break;
}
}
}
Implement View.OnClickListener on your class and override its onClick method. That would make the code somewhat cleaner.
But first i recommend you to have proper knowledge of OOP and Java.
You just need to implement the OnClickListener interface and override the onCLick method. And on your onCLick() method you just need to add a filter for the corresponding View.
public void onClick(View arg0){
if(arg0 == myButton){
//do stuff when myButton is click
}else if(arg0 == myOtherButton){
//do stuff when myOtherButton is click
}
}
- What you have encountered is know as Anonymous Inner Class.
Anonymous Inner Class:
It has no name.
It must implements or extends one and only one Interface or Class respectively.
- This is just a way of coding where you keeping the functionality of that view or component attached visually.
The another way you can do that is by doing the following:
- Implement the specific Interface that has the call-back method.
public class MainActivity implements OnItemClickListener{
private Button buttonClick;
....
....
onCreate(Bundle saveInstance){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_view);
buttonClick = (Button)findViewById(R.id.button_click);
buttonClick.setOnClickListener(this);
...
...
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_click:
// -------- Do you function here
break;
}
}
}