Dynamically populate a button value android - android

I have seen lots of example to which one use a if condition or a case statement to programmatically change the conditions of elements...yadda yadda. I need to change the value of a button based on what the user clicks. Below is the code that I currently have.
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){CONTINUES TO OTHER FUNCTIONS }
I basically need to know what button was pressed. Then dynamically populate it into findViewById() function. i.e.
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
This way by the time it gets to the final Button part of the code it will have the value to which the user clicked on. Code works if I only want to have one button or a page mile deep in different configuration (not ideal).
All the examples I have seen so far are after the user clicks the button (which is what I want) but they name the buttons name statically like above code shows but very much static.
Hope that all makes sense.
UPDATE:
I think I may have confused the situation. Below is the remaining code. Hopefully this will provide context. The btnOpenPopup needs to remain the same as it's used in the call to execute the command for a new window to actually popup. Hopefully this will provide a bit more context for what I'm trying to achieve.
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.meditationpopup, null);
//set the title of the popup
TextView titletext = (TextView) popupView.findViewById(R.id.chakratitle);
titletext.setText(activityName);
if (activityName.equals("Root"))
{
switch (arg0.getId())
{
case R.id.color:
//Rename the string so to get the value from the string xml
String stringName = activityName.toLowerCase().replaceAll(" ","")+"color";
TextView desctext = (TextView) popupView.findViewById(R.id.popupDesc);
desctext.setText(getString(getStringResource(getApplicationContext(),stringName)));
break;
case R.id.polarity:
//Rename the string so to get the value from the string xml
String polarityString = activityName.toLowerCase().replaceAll(" ","")+"polarity";
TextView polarityDesc = (TextView) popupView.findViewById(R.id.popupDesc);
//polarityDesc.setText(activityName);
polarityDesc.setText(getString(getStringResource(getApplicationContext(),polarityString)));
break;
}
}

I think
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
should be
Button btnOpenPopupFirst = (Button)findViewById(R.id.polarity);
Button btnOpenPopupSecond = (Button) findViewById(R.id.color);
you should declare different different button for diffrerent findviewbyid
also in my eclipse it is not accepting
btnOpenPopup.setOnClickListener(new Button.OnClickListener()
instead it works with
btnOpenPopup.setOnClickListener(new View.OnClickListener() {}
and you need to provide more clear view of what you want to perform
new thoughts,try doing this:
btnOpenPopupFirst.setOnClickListener(this);
btnOpenPopupSecond.setOnClickListener(this);
then option will come on both the above code lines
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (MainActivity)
choose this
let MainActivity implement OnClickListener
then this option will come
The type MainActivity must implement the inherited abstract method View.OnClickListener.onClick(View)
choose
add unimplemented method
now
#Override
public void onClick(View v)
will be created
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.polarity:
Toast.makeText(getApplicationContext(), "btnOpenPopupFirst(polarity) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
break;
case R.id.color:
Toast.makeText(getApplicationContext(), "btnOpenPopupSecond(color) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
default:
break;
}
}
And post your views after implementing this way.

int[] id={R.id.button1,R.id.button2};
Button b=(Button)findViewById(id[i]);

The onClick method in Button.OnClickListener has a View parameter... you can call getId() on that view to get the id of that button that was clicked on.

It doesn't make too much sense to me. If what you really want is this:
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
All you need to do is set your value in the onClick(View view) method of your OnClickListener
public void onClick(View view) {
btnOpenPopup = (Button)view;
}

Related

Button to hide a TextView

I've been searching for a solution for this for a while but cannot seem to get one working. There are one or two on here about this subject but I can't seem to get them going. I'm also a novice in Android and while I've been on and off playing with it for a few years, I still understand next to nothing about what I'm writing.
Basically I've got a TextView and a button. Ideally I'd like to put some text in the TextView, press a button it's gone, press the button again and it's back.
I've narrowed it down to needing to understand what findViewById(R.id.button2) does but honestly I'm a bit lost.
I've added my button code but apologies that this is such a noob question
public void onClick(Button v){
TextView t1 = (TextView)findViewById(R.id.editText);
v.setVisibility(View.GONE);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView t1 = (TextView)findViewById(R.id.TextView);
v.setVisibility(View.GONE);
}
});
}
Your code has a couple of issues. I'm not going to give you the code because that won't really help you learn. Instead I'll explain things and let you try to figure it out or come back with more explicit questions.
You know that xml file you set using setContentView? Some of the tags in it had a property android:id="xxxx". That xxxx is the id of that view, its used so you can find that view in your code. The findViewById function walks through all the views on screen and finds a view with that id and returns it. That gives you a reference to the view so you can change it. For example, you can set its visibility, set its background color, or set an OnClickListener.
So to have a button toggle the visibility of another view, you need to be able to do the following things:
1)Find the view who's visibility you want to change
2)Figure out what its visibility currently is
3)Figure out what you want it to be (the opposite of what it currently is
4)Set that visibility
You need to write a function that does all that. Then you need to do this
1)Find the button you want to use to change the visibility
2)Tell it to call your function when its pressed.
Figure out how to do each of those steps individually, and you should be able to put it together. Good luck.
findViewById(R.id.button2) finds the view with the id button2.
You can check inside onClick whether t1 is visible or not (t1.setVisibility(View.GONE); not v.setVisibility(View.GONE);), and toggle between View.GONE and View.VISIBLE.
Remember that your findViewById() should have a real id. They are normally set on the activity_name.xml.
You are using a onClick inside a onClick. Personally I recommend setting the listener manually with setOnClickListener.
There's a lot of work for you, start with these tutorials. Keep trying and try to understand what you are doing.
Look like you need a toogle button feature, here is a piece of code.
Important: you must pay heed to #GabeSechan and #SkyDriver2500 answers.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//your other code
Button button = (Button) findViewById(R.id.button2);
final TextView t1 = (TextView) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
t1.setVisibility(t1.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
}
});
}
I'm not sure if the code will help you now. But just in case, here it is
final boolean[] isTvVisible = {false};
final TextView t1 = (TextView)findViewById(R.id.editText);
t1.setVisibility(View.GONE);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isTvVisible[0]) {
t1.setVisibility(View.GONE);
isTvVisible[0] = false;
} else {
t1.setVisibility(View.VISIBLE);
isTvVisible[0] = true;
}
}
});

Runtime onClicklLstener android

Just wondering can anyone solve this problem about adding listeners to imagebuttons at runtime. I'm presuming it has got something to do with the "this" parameter passed to setOnClickListener as we are already in a onClickListener.
My fragment implements onclicklistener. The onClick methods work for imagebuttons known at compile time, just not for the ones that are defined after inflating a prompt view. What seems to happen is the prompt layout seems to be recreated and added onto the back stack.
Basically the onclicklistener for mWhatsappshare,mEmail share does not react as I might expect. I put a stackoverflow error in the onclick method previously and when I clicked these imagebuttons my application did not crash. This means that the listener is in fact not registered (or at least not correctly) at
mwhatsapp.setonclicklistener(this)
By the way, I do not want to set separate listener like mWhatsapp.setonclicklistner(new View.onClickListener()){ for each imagebutton as it is too cumbersome and I want each listener to be handled in onclick().
Thank you
mOtherShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeColorFilters();
mOtherShare.setImageResource(R.drawable.other_pill_pressed);
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.share_prompt,null);
mWhatsappShare = (ImageButton) dialoglayout.findViewById(R.id.ib_whatsapp_share);
mEmailShare = (ImageButton) dialoglayout.findViewById(R.id.ib_email_share);
mFlickrShare = (ImageButton) dialoglayout.findViewById(R.id.ib_flickr_share);
mTumblrShare = (ImageButton) dialoglayout.findViewById(R.id.ib_tumblr_share);
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(dialoglayout);
dlg = builder.show();
mWhatsappShare.setOnClickListener(this);
mEmailShare.setOnClickListener(this);
mFlickrShare.setOnClickListener(this);
mTumblrShare.setOnClickListener(this);
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ib_whatsapp_share:
sendIntent("com.whatsapp");
break;
case R.id.ib_email_share:
sendIntent("android.email");
break;
case R.id.ib_flickr_share:
sendIntent("com.yahoo.mobile.client.android.flickr");
break;
case R.id.ib_tumblr_share:
sendIntent("com.tumblr");
break;
}
}
``
On this block of code:
mWhatsappShare.setOnClickListener(this);
mEmailShare.setOnClickListener(this);
mFlickrShare.setOnClickListener(this);
mTumblrShare.setOnClickListener(this);
this is referring to the new OnClickListener you are creating - mOtherShare.setOnClickListener(new View.OnClickListener() and NOT your fragment's OnClickListener
To use the outer onClick, change this to YourFragment.this

setOnClickListener for a button inside onOptionsItemSelected causing app crash

I am invoking from a menu Item a Dialog and I have a Button inside that Dialog and trying to do something when I press the button. The part of my code for this is as followed:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itTip:
final Dialog tipCalculator = new Dialog(this);
tipCalculator.setTitle("Tip Calculator");
tipCalculator.setContentView(R.layout.tip_layout);
totalBill = (EditText) findViewById(R.id.editTBill);
tips = (EditText) findViewById(R.id.editTTip);
calculate = (Button) findViewById(R.id.bCalcTip);
tvResult = (TextView) findViewById(R.id.tvTipResult);
calculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Calculate clicked", Toast.LENGTH_SHORT).show();
}
});
tipCalculator.setCancelable(true);
tipCalculator.show();
break;
}
return super.onOptionsItemSelected(item);
}
When I run my app, without the setOnClickListener, it works fine and shows the Dialog perfectly. But whenever I am trying to use the Listener, it crashes. I checked in LogCat and could actually not understand the problem clearly. Hope anyone can help me here.
I think the problem is because you attempt to find the view before you have actually shown it, this causes 'calculate' to be null when attempting to assign a onClickListener, and thus throws a null pointer exception.
To explain in a bit more detail, findViewById searches all the views currently being displayed and returns the view that matches that id. The button is contained in R.layout.tip_layout, but that view is not inflated until tipCalculator.show() is called and it won't be included in the list of views searched, so findViewById returns null.
There are a few approaches you could take to make this work, but I think the following would require the least alterations to your original code:
case R.id.itTip:
final Dialog tipCalculator = new Dialog(this);
tipCalculator.setTitle("Tip Calculator");
View contentView = View.inflate(this, R.layout.tip_layout, null);
totalBill = (EditText) contentView.findViewById(R.id.editTBill);
tips = (EditText) contentView.findViewById(R.id.editTTip);
calculate = (Button) contentView.findViewById(R.id.bCalcTip);
tvResult = (TextView) contentView.findViewById(R.id.tvTipResult);
calculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Calculate clicked", Toast.LENGTH_SHORT).show();
}
});
tipCalculator.setContentView(contentView);
tipCalculator.setCancelable(true);
tipCalculator.show();
break;
What we do different is inflate the view in advance (contentView) and define where to find each widget by searching that view specifically.

<ToggleButton> onClickListener - Create/Delete button + add content to button

I have this problem with my ToggleButton.
I want it to create/delete a button upon being toggled, and at the same time add content/functions to the button, like drawable and such.
This is the current code:
public class BillardScoreboardActivity extends Activity {
/** Called when the activity is first created. */
Button minuskegle, minuskugle, pluskugle, pluskegle, plusmidkegle, minusmidkegle, miss;
ToggleButton toggle;
LinearLayout bottomlayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toggle = (ToggleButton) findViewById(R.id.bRedGreen);
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pluskugle = (Button) findViewById(R.id.bBallhole);
minuskugle = (Button) findViewById(R.id.bBallhole);
pluskegle = (Button) findViewById(R.id.bKegle);
minuskegle = (Button) findViewById(R.id.bKegle);
plusmidkegle = (Button) findViewById(R.id.bKeglemid);
minusmidkegle = (Button) findViewById(R.id.bKeglemid);
bottomlayout = (LinearLayout) findViewById(R.id.bottomlayout);
miss = (Button) findViewById(R.id.bMiss);
if(toggle.isChecked())
{
minuskugle.setBackgroundResource(R.drawable.redballinhole);
minuskegle.setBackgroundResource(R.drawable.redkegle);
minusmidkegle.setBackgroundResource(R.drawable.midkegleminus);
miss.setBackgroundResource(R.drawable.missbutton);
miss.setVisibility(View.VISIBLE);
}
else
{
pluskugle.setBackgroundResource(R.drawable.whiteballinhole);
pluskegle.setBackgroundResource(R.drawable.kegleb);
plusmidkegle.setBackgroundResource(R.drawable.midkegleplus);
miss.setVisibility(View.GONE);
}
}
});
}
The current problem is that it can't find the (buttontest) in this part of the code:
else
{
pluskugle.setBackgroundResource(R.drawable.whiteballinhole);
pluskegle.setBackgroundResource(R.drawable.kegleb);
plusmidkegle.setBackgroundResource(R.drawable.midkegleplus);
bottomlayout.removeView(buttontest);
}
And as mentioned earlier, the second problem is to make the button inherit some functions/content.
for bigger version: http://i.imgur.com/KxKvh.png
Btw... Everytime i start up the application, it gives me 2 apps to choose between, whereof only the bottom one works:
I guess the problem is that the togglebutton's initial state is 'checked'. That means when you click it the first time, isChecked() will return false and the else-part of your code will be executed. But at that point, buttontest hasn't been added to bottomlayout yet.
I recommend you to have the button inside the layout by default and call buttontest.setVisibility(View.GONE) when you would like to hide it and buttontest.setVisibility(View.VISIBLE) when it needs to be shown.
As for your second question, just call setBackgroundResource/Drawable to add content (like you're already doing it with the other buttons). If you say you want to add functionality, I assume you intend to do something when the button is clicked? If yes, add a View.OnClickListener.
Hope I could help you.

ParseInt Exception

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;
}

Categories

Resources