Working with buttons in android - android

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
}

Related

Intent GridLayout to 4 Activities

I have GridLayout with a CardView inside. I want to create an Intent to 4 different activities. I only can execute one Intent. I do not know if I should use Else If or case. Thanks for your help. Here is my code.
GridLayout mainGrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
mainGrid = (GridLayout)findViewById(R.id.grid);
setSingleEvent(mainGrid);
}
private void setSingleEvent(GridLayout mainGrid) {
for (int i=0;i<mainGrid.getChildCount();1++)
{
CardView cardView = (CardView)mainGrid.getChildAt(i);
final int final1= i;
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(DashboardActivity.this,MapsActivity.class);
startActivity(i);
}
});
}
}
I think your problem comes from a lack of understanding how the order of execution of the program works. If you insert a cycle for and then you put inside an anonymous class as it is the case of View.onViewClickListener is normal that you will have only one result, because you break the for cycle.
The way to go should be to not use a for cycle, but assigning different Explicit Intents depending by what you want to obtain.
EDIT. On the base of your use case you need to trigger the Intent from the Adapter. Please see here and mainly here, basically you need to use the Android SDK functionality that tells you which card has been clicked mRecyclerView.getChildLayoutPosition(view); then depending from your needs you may (or not) pass a switch case for educational purposes, although possibly is not the most elegant and efficient way to solve.
If you want a different Activity to be started depending on what CardView is clicked try something like the following:
private void setSingleEvent(GridLayout mainGrid) {
mainGrid.getChildAt(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(i);
}
});
mainGrid.getChildAt(1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(i);
}
});
//do this for all 4 cardViews.
}
In short: set all Intents separately.

Android setOnClickListener method - How does it work?

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/

How to activate Text-To-Speech when clicked on TextView?

the question is as above.
scenario : i programmatically created table rows with text view in it. i wanted to allow text-to-speech when i clicked on the textview. there is some reason for not using listview. i tried to use button for easier usage, however the button that i created is always out of the dimension that gave. so, i wanted to use textview to activate the TTS.
how do i do that ?
i tried using
tv.setOnClickListener(new OnClickListener()
{
public void OnClick(View v)
{
String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null);
}
});
i uses for-loop for it, so that it will create a table row for every data collected. the problem is, it requested the "i" to be final. and when i made it final, i cant use i++.
please help. thanks alot =)
Try to declare your int i; in your class. I believe this will help you to avoid of using final modifier.
public class MyActivity extends Activity {
int i;
public void onCreate(Bundle savedInstanceState) {
...
tv.setOnClickListener(new OnClickListener()
{
public void OnClick(View v){
String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null);
}
});
...
}
}
or put this code String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null); to another method. for example:
tv.setOnClickListener(new OnClickListener()
{
public void OnClick(View v){
speak();
}
});
__
public void speak(){
String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null);
}

How do you Override onClick in an Android ImageButton derived class

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.

Java error with the Google Android "HelloFormStuff" tutorial

I am a java neophyte. I followed the tutorial at http://developer.android.com/resources/tutorials/views/hello-formstuff.html to add a button and OnClick handler by copying the tutorial code into mine:
public class FormStuff extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton button = (ImageButton) findViewById(R.id.android_button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(FormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
}
}
In Eclipse this produces two errors
Description Resource Path Location Type
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){}) FormStuff.java /FormStuffExample/src/com/example/formstuffexample line 17 Java Problem
The type new DialogInterface.OnClickListener(){} must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int) FormStuff.java /FormStuffExample/src/com/example/formstuffexample line 17 Java Problem
What am I doing wrong? Thanks!
Based purely on the error messages...
You're using the (implicitly) the wrong OnClickListener interface/class. It looks like there are two, View.OnClickListener and DialogInterface.OnClickListener.
The solution is to fully qualify your annonymous OnClickListener.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(FormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});
Thanks Kevin. Followed your suggestion I fixed my error too. Eclipse offers too many hints and a newbie like me have no idea what should I choose. Later, I found another solution. If Eclipse cannot import the required when you hit O, you should manual add it:
import android.view.View.OnClickListener;

Categories

Resources