I've seen this asked a thousand times in a thousand different ways, but still can't get it to work...
I created a class which I've derived from ImageButton. I want to define my "on-click" behavior in the class.
I know I can do something inside my Activity's onCreate like:
myButton b;
b = (myButton)findViewById(R.drawable.mybutton);
b.setOnClickListener(new View.OnClickListener() {
...etc...
but I want to define the code where it should be, in the derived class.
I first thought I could define it as:
#Override public void onClick(View v) {
...but I get an error saying that I can't use "#Override" here because "onClick" isn't in the superclass. (When trying to remove "#Override", it just builds and runs, but never gets called). I've also tried:
#Override public void onClickListener(View v) {
...and several variants of "implements onClickListener" and "implements OnClickListener" to no avail.
This should be fairly simple - any ideas??
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
derivedClassFunction(v);
}
});
public void derivedClassFunction(View v) {
/* code...*/
}
Another way:
public class DerivedClass extends ImageButton implements View.OnClickListener {
/*code...*/
b.setOnClickListener(this);
/*code...*/
#Override
public void onClick(View v) {
/*code...*/
}
}
This is because there actually is no method onClick() in views. The work is done in the onUpKey() in the View class.
However, if you want to listen to clicking events in the subclass, this could be done very easily. You can either create an inner class which implements View.OnClickLister and use it to listen to events or even simpler, implement the interface in your class and set it as a listener during construction. The latter will look like this:
class YourClass extends ImageButton implements View.OnClickListener {
public YourClass() {
setOnClickListener(this);
}
#Override
public void onClick(View v) {
//Your code
}
}
LAS_VEGAS has already posted how the first variant with the inner class may look like.
Related
I have been coding for a very long time and I've only started using Android Stud last month, I'm having a problem with implementing an OnClickListener.
here's the code that is giving me the error.
I hope my question is clear, else I'll happy to give my code snippet.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button scanBnt;
private TextView formatText, contentText;
....
}
You have implemented View.OnClickListener interface in your activity. This interface has one abstract method abstract void onClick(View v) which you need to override in your activity.
Add the following code to your activity,
#Override
public void onClick(View v) {
// Your code
}
Check out
Button button = (Button) findViewById(R.id.mybutton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show();
}
});
for explanation visit here
Highlight on the error (OnClickListener) then press Ctrl + Space then click implement method. else you can add the method manually like what #gprathour written.
Is this generally a good practice to adopt?
I am working through the tutorials and got to the part where button listeners are being implemented:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button) findViewById(R.id.true_button);
//and here is the anonymous inner class
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
Am I better off learning this style or is there another way I should be learning this for the sake of good practice? It seems a little counter to my basic understanding of OOP where things seem to be... separated and modularized, if that makes sense.
Yes, there is another way that I often prefer (especially in big projects), your class can implement listeners
So your Activity/Fragment can be declared this way
public class MyActivity implements View.OnClickListener{
and your view object, button in this case, would set it's listener this way
mTrueButton.setOnClickListener(this)
and then you would have another class called onClick() where ALL of your clickable view elements can now have their code
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.true_button:
break;
}
}
If I want to design a button that all java can use it without need to write it in every java,
what should I do?
For Example:
I design a Button.OnClickListener function to search bluetooth devices.
but another java also need to use this Button.OnClickListener function,
I don't want to write same way on two java.
ledWrite.xml:
<Button android:id="#+id/btnScan" />
<ToggleButton android:id="#+id/tBtnWrite" />
bluetoothUtils.java
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private Button button_scan;
button_scan = (Button)findViewById(R.id.button_scan);
button_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
scanbt();
}
});
private void scanbt(){
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
then I design LedWrite.java:
private ToggleButton digitalOutBtn; //LED On/OFF
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ledwrite);
digitalOutBtn = (ToggleButton)findViewById(R.id.tBtnWrite);
digitalOutBtn.setOnClickListener(new OnClickListener()
public void onClick(View v){
if(digitalOutBtn.isChecked()){ //sendMessage("D1"); }
else{sendMessage("D0";}
}
How can I use button_scan in LedWrite.java?
If you want to call a method defined is some other Activity on press of a button, then you can make that method as static.
Let's assume that you have a method named searchBluetooth() in MainActvity and you want to call it from SecondActivity.
Define searchBluetooth() in MainActvity like,
public static void searchBluetooth()
Call this method from SecondActivity like,
MainActivity.searchBluetooth()
If you don't want to use static because of memory consumption then try with inheritance.
Create a class CommonActivity which extends Activity class
class CommonActivity extends Activity
{
// here define your searchBluetooth method
public void searchBluetooth()
{
// your code here
}
}
If you want to make use of it in Second Activity then
class SecondActivity extends CommonActivity
{
// here you can access `searchBluetooth()` method
}
enclosure a BluetoothListener class?
public BluetoothListener implements OnClickListener {
#Override
public void onClick(View v) {
do something you want...
}
}
then invoke the class in two different class, eg,
button.setOnClickListener(new BluetoothListener());
I recently started learning android and this answer may have some error, if so, please let me know, Thanks.
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/
Alright, so i've been making great progress on the app i'm trying to create, but most of the tutorials that i've been learning from only showcase the wondrous feature of having only one active widget inside the application at a time...
The thing is, my application requires 2 or more buttons and that's the part i'm partially stuck at. My code implements a "SetWordsBtn" shown below (everything else is declared),
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn);
SetWordsBtn.setOnClickListener(this);
}
which implements a onClick() like this:
public void onClick(View view) {
startWords();
}
but what if i have another button that deletes the words such as "DelWordsBtn"? I was thinking i could declare both buttons simultaneously like this:
SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn);
DelWordsBtn=(Button)findViewById(R.id.DelWordsBtn);
SetWordsBtn.setOnClickListener(this);
DelWordsBtn.setOnClickListener(this);
but what about the onClick() method? Does it automatically apply itself to both the buttons when i do this?
How am i able to declare a seperate onClick from each other so it both does different stuff when i click on either one of them?
I was thinking the answer could be something like this, but i dunno :
//Declarations
SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn);
DelWordsBtn=(Button)findViewById(R.id.DelWordsBtn);
SetWordsBtn.setOnClickListener(setWordsView);
DelWordsBtn.setOnClickListener(delWordsView);
//onClick Functions
public void onClick(View setWordsView) {
startWords();
}
public void onClick(View delWordsView) {
deleteWords();
}
So it would actually link the startWords() function to the SetWordsBtn, and deleteWords() to DelWordsBtn...
Any clear cut explanation/form of help would be appreciated. Thanks in advance guys. :)
The typical convention is to just switch off of the ID of the View that is clicked. For example:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(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);
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(new View.OnClickListener() {
public void onClick(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.
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
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:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but=(Button)findViewById(R.id.button1);
}
public void callme(View v)
{
//Do somthing
}