EditText etHomePhone = (EditText)findViewById(R.id.et_pi_home_phone);
EditText etMobilePhone = (EditText)findViewById(R.id.et_pi_home_phone);
etHomePhone.setOnClickListener(showPopUpClickListener);
etMobilePhone.setOnClickListener(showPopUpClickListener);
private View.OnClickListener showPopUpClickListener = new View.OnClickListener() {
public void onClick(View v) {
/* I like to get both EditText.getText().toString() value in this one ClickListener
is it Possible, there is something in ActionScript call event.currentTarget...
*/
}
};
If you declare your etHomePhone and etMobilePhone variables as final and define your OnClickListener inline in the same method, then you can refer to those variables directly. Like so:
final EditText etHomePhone = (EditText)findViewById(R.id.et_pi_home_phone);
final EditText etMobilePhone = (EditText)findViewById(R.id.et_pi_home_phone);
View.OnClickListener showPopUpClickListener = new View.OnClickListener() {
public void onClick(View v) {
String home = etHomePhone.getText().toString();
String mobile = etMobilePhone.getText().toString();
// Do something with home and mobile
}
};
etHomePhone.setOnClickListener(showPopUpClickListener);
etMobilePhone.setOnClickListener(showPopUpClickListener);
EDIT:
If you only want to get the text for the EditText that was clicked instead of both of them, then you can just cast the View that it delivered via onClick(View v):
public void onClick(View v) {
EditText editText = (EditText)v;
String phoneNumber = editText.getText().toString();
// Do something with phoneNumber
}
This is a snippet, so I can't see the context but you can structure a single OnClickListener to catch all events in your activity. First, your activity will need to implement the OnClickListener interface:
public class YourActivity extends Activity implements OnClickListener {...
In the OnCreate() method, register each UI element which should respond to clicks like this:
yourObject.setOnClickListener(this);
Next, for the activity's onClick() method, create a switch structure using R.id like this:
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.A_UI_Element:
//do what you need for this element
break:
case R.id.A_Different_UI_Element:
//do what you need for this element
break;
//continue with cases for each element you want to be clickable
}
}
Don't forget the break at the end of each case.
One thing I noticed in your code: both editText declarations refer to the same resource. This gives you two handles to the same UI element, not 2 different elements.
Related
Good morning,
How can I put multiple string ressources inside the setText to display them in order ?
I have a layout with a TextView (id: TxtDisp) and a Button (id: NextSentence) that change the text when I click on it.
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TxtDisp.setText(R.string.sentence_2);
}
});
Where or how can I put four to six string ressources to be display in order when the button is clicked ?
Thanks in advance !
You could put the string resources in an array, and get the string from that. So add a class member to track the which sentence is next
private int nextSentenceId = 0;
then in onCreate use code like this
final int[] sentences = new int[]{R.string.sentence_1, R.string.sentence_2, R.string.sentence_3};
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( nextSentenceId < sentences.length ) {
TxtDisp.setText(sentences[nextSentenceId]);
++nextSentenceId;
}
}
});
Make sure to catch when you are at the last sentence or you will get an array out of bounds error.
You can do it easily when you hold these strings in an array or something and have a counter that hold which string is displayed right now like so
in onCreate() method put your sentences in an ArrayList
ArrayList<Integer> strings = new ArrayList();
strings.add(R.string.sentence1);
strings.add(R.string.sentence2);
strings.add(R.string.sentence3);
then on the button click you can use the counter and track which is selected
NextSentence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TxtDisp.setText(strings.get(count++));
}
});
I hope this would help you
I want to make button unclickable using setClicable() but it's not working. I am using inflater because I need.
This is my code:
mContactList = (LinearLayout) findViewById(R.id.contactList);
LayoutInflater inflater = getLayoutInflater();
for (ListIterator<ContactModel> it = contactList.listIterator(); it.hasNext();){
ContactModel contact = it.next();
View view = inflater.inflate(R.layout.contact_unknown_list_row, null);
view.findViewById(R.id.inviteButton).setTag(contact.getEmail());
view.findViewById(R.id.inviteButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String address = (String) v.getTag();
sendInvatoin(address);
if(v.findViewById(R.id.inviteButton).isClickable())
v.findViewById(R.id.inviteButton).setClickable(false);
}
});
mContactList.addView(view);
}
Try using.
button.setEnabled(false);
In your case, you will do something like this:
view.findViewById(R.id.inviteButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String address = (String) v.getTag();
sendInvitatoins(address);
Button b = (Button)v;
b.setEnabled(false);
}
});
When using setOnClickListener, unclickable views (= v.setClickable(false)) would become clickable as mentioned in Docs.
... a callback to be invoked when this view is clicked. If this
view is not clickable, it becomes clickable.
Better to use v.setEnabled(false) if you want to set an OnClickListener to the button or any other view...
This will work in case of Imageview as well as the button.
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (imageview.isEnabled()){
//I have wrapped all code inside onClick() in this if condition
//Your onClick() code will only execute if the imageview is enabled
//Now we can use setEnabled() instead of setClickable() everywhere
}}
};
Inside onCreate(), you can do setEnabled(false) which will be equivalent to setClickable(false).
We are able to use setEnabled() as tag because it's state remains unaffected on invocation of click (unlike setClickable() whose state changes).
I am creating a small calc app with EditText views and Im running into an runtime exception when the user leaves an EditText view empty causing the ParseInt to try and Parse nothing. Ive read that I need to 'Try' and 'Catch' this error before it occurs, but Im unsure of where and how to do this!
Any advice is much appreciated!
Here is my code:
public class HandlerExamples extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.testButton);
button.setOnClickListener(this);
public void onClick(View v) {
String a,b,t;
double vis;
EditText txtbox1 = (EditText)findViewById(R.id.A);
EditText txtbox2 = (EditText)findViewById(R.id.B);
EditText txtbox3 = (EditText)findViewById(R.id.t);
TextView tv = (TextView) findViewById(R.id.Answer);
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
t = txtbox3.getText().toString();
vis = ((Integer.parseInt(a)*1) + (Integer.parseInt(b)*2)) / (Double.parseDouble(t));
tv.setText(double.toString(vis));
}
}
Thanks so much!
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.xx:
//do things xx click
break;
case R.id.yy:
//do things yy click
break;
}
}
you can get the view id to know whick widget was clicked.
Changwei Yao defined one way you can do this, but here's the way most Android programmers would do this (programmatically), since it's a little easier to read and figure out what your widgets are doing:
But first, remove the implements OnClickListener from your Activity, as it's not needed.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// what you want your button to do when clicked
}
}
editText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// what you want your EditText to do when clicked
// (such as editText.setText(""))
}
}
Another way to do the same thing is to define android:onClick="insert_method_name_here" for the widgets that you want perform an action when clicked. In your case, in your main.xml (since that's what you're using in your Activity), you could write something like...
<Button android:id="#+id/testButton"
(other attributes you wish to apply to the button)
android:onClick="buttonAction" />
<EditText
(other attributes)
android:onClick="textAction" />
And then, in your Activity, you define the methods buttonAction(View v) and textAction(View v). Note that these methods must be public void, and must take the sole argument View v.
(One advantage of the XML method is that you don't necessarily have to define an android:id attribute for these widgets, unless you need to be able to manipulate them or extract information from them in your code (which means you will need to define an android:id for your EditText since you'll likely want the user's input))
If you only need to exclude the empty text field then hotveryspicy's solution is probably the quickest. For a secure solution: catching the NumberFormatException will filter anything that can not be converted to an integer.
int vis;
try {
vis = Integer.parseInt(a);
}
catch(NumberFormatException nfe) {
Log.e(TAG,"trying to convert:"+a+" to integer failed");
vis = 0;
}
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
Is there a way to have 1 onClick Lister for many buttons where I can toss a case statement to do things based on what buttons were clicked.
I know I can make 100 different listeners for 100 buttons but I have to think I can create some nifty variables to do it in less lines of code.
Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};
If you are using 1.6+ version of the SDK you can use android:onClick to set the onClick handler of a view. In your activity you must have a method with the following signature. The view is the view that was clicked.
void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
//do something fantastic;
break;
}
}
public class MainActivity extends Activity implements View.OnClickListener{
btnXXX.setOnClickListener(this);
public void onClick(View v) {
if (v.getId()==R.id.btnXXX){
dialog.show();
} else {
handleOtherViews(v);
}
}
Alternatively, you can specify the method to call in xml:
<Button android:id="#id/button" android:text="#string/button" android:onClick="someMethod" />