Problems setting the content description to image button - android

Hello i am trying to set a content description to my button buy when i try to access to it the value that return to me is null.
Here is the code of the button.
//This is the button of the payment.
ImageButton make_pay = new ImageButton(this);
make_pay.setBackgroundResource(R.drawable.add_product);
makePay.addView(make_pay);
makePay.setContentDescription("Precio");
This is the code that i use to access:
make_pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View makepay) {
LinearLayout wrap_area = (LinearLayout)findViewById(R.id.division2);
TextView test = new TextView(FrontActivity.this);
wrap_area.addView(test);
if (makepay.getContentDescription() == null){
test.setText("Precio:1");
}else{
test.setText(makepay.getContentDescription().toString());
}
});
}

You are setting the content description to makePay object (whatever it is, probabbly a ViewGroup). But then, you are setting the listener to the make_pay ImageButton, which is the one received by the listener arguments. Thus, it's content description is not the one assigned to the other object.
Try changing this:
makePay.setContentDescription("Precio");
with this:
make_pay.setContentDescription("Precio");
Anyway, try not to name your objects in such a similar way. It could lead to big confussions.

Related

Android Development - Create a menu with 3 imageButtons

First of all english is not my first language but i will try my best.
Also... i am pretty sure my title choice was not the best so sorry for that.
Basically what i wanted to do is a menu with three ImageButtons but there is a tricky part (tricky for me at least) since every time i press one button that same button changes image (to a colored version instead of a grayed out image) and the other two change as well from colored version of their respective images to grayed out ones, actually only one of the other two will change since the purpose of this is to be able to activate only one at a time so it would not be possible to have the other two active at the same time.
Notice that this is not a menu on the top right corner but just a set of three ImageButtons on a activity or Fragment.
I already tried a lot of stuff to make that happen but so far no luck but i think i know why though i can't find a workaround for this since i am actually new in android dev.
what i tried was inside the setOnClickListener of any of those buttons such as:
eventsButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ImageButton eventsButton = (ImageButton) view.findViewById(R.id.eventsButton);
eventsButton.setBackgroundResource(R.drawable.events_icon_active);
eventsButton.setClickable(false);
}
}
);
i tried to add the functions to change the other imageButtons as well like:
eventsButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ImageButton eventsButton = (ImageButton) view.findViewById(R.id.eventsButton);
eventsButton.setBackgroundResource(R.drawable.events_icon_inactive);
eventsButton.setClickable(false);
ImageButton contactsButton = (ImageButton) view.findViewById(R.id.contactsButton);
contactsButton.setBackgroundResource(R.drawable.contacts_icon_inactive);
contactsButton.setClickable(true);
ImageButton interestsButton = (ImageButton) view.findViewById(R.id.interestsButton);
interestsButton.setBackgroundResource(R.drawable.interests_icon_inactive);
interestsButton.setClickable(true);
}
}
);
and i repeated that three time, always setting the other buttons clickable and setting their images to the inactive one (the grayed out one), also setting the button i click as no longer clickable.
But from what i gather i cant do any references to any other buttons inside the eventsButton.setOnClickListener like the buttons interestsButton or contactsButton, it will crash the app as soon as i touch any of those three buttons with the following error message:
Attempt to invoke virtual method 'void android.widget.ImageButton.setBackgroundResource(int)' on a null object reference
And it always point to the first line where i make a reference to another button other then the one used to start the setOnClickListener.
If you can just point me in the right direction i would be tremendously grateful.
All the best
You can declare your ImageViews as final outside the scope of the listener and when the onClickListener(View v) is called you can then just call setBackground because they are final and you can reference them from inside the listener.
Something like this:
final ImageView view1 = (ImageView) findViewById(R.id.view1id);
final ImageView view2 = (ImageView) findViewById(R.id.view2id);
view1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
// do whatever you want to the ImageViews
// view1.setBackground...
}
}
);
eventsButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
ImageButton contactsButton = (ImageButton) view.findViewById(R.id.contactsButton);
contactsButton.setBackgroundResource(R.drawable.contacts_icon_inactive);
contactsButton.setClickable(true);
}
}
);
Your problem is in view.findViewById(R.id.contactsButton): view here is the button being clicked (the events one), and by calling view.findViewById(contactsButton) you are implicitly saying that the contact button is a child of view, which is not.
Just use findViewById() (from Activity), getActivity().findViewById() (from Fragments), or better container.findViewById() (if you have a reference to the layout containing the three buttons).
I'm not saying that yours is the most efficient way to deal with a menu, just pointing out your error.
You can first make things simple; I suggest:
you add 3 array (Arraylist might be better) fields in your activity class, one for the buttons, one for the active resources and one for the inactive resources
initialize those arrays in the onCreate method;
define a single onClickListener object and use it for all the buttons; Use a loop in the onClick method, see bellow.
In terms of code, it looks like this:
ImageButton[] buttons;
int[] activeResources;
int[] inactiveResources;
protected void onCreate2(Bundle savedInstanceState) {
View.OnClickListener onClickListener = new View.OnClickListener(){
public void onClick(View view) {
ImageButton clickedButton = (ImageButton) view;
for(int i = 0; i<buttons.length; i++){
ImageButton bt = buttons[i];
if(clickedButton==bt){
bt.setBackgroundResource(inactiveResources[i]);
bt.setClickable(false);
}else{
bt.setBackgroundResource(activeResources[i]);
bt.setClickable(true);
}
}
}
};
buttons = new ImageButton[3];
activeResources = new int[3];
inactiveResources = new int[3];
int idx = 0;
buttons[idx] = (ImageButton) findViewById(R.id.eventsButton);
inactiveResources[idx] = R.drawable.events_icon_inactive;
activeResources[idx] = R.drawable.events_icon_active;
idx = 1;
buttons[idx] = (ImageButton) findViewById(R.id.contactsButton);
inactiveResources[idx] = R.drawable.contacts_icon_inactive;
activeResources[idx] = R.drawable.contacts_icon_active;
idx = 3;
buttons[idx] = (ImageButton) findViewById(R.id.interestsButton);
inactiveResources[idx] = R.drawable.interests_icon_inactive;
activeResources[idx] = R.drawable.interests_icon_active;
for(int i =0; i<buttons.length; i++){
buttons[i].setBackgroundResource(activeResources[i]);
buttons[i].setOnClickListener(onClickListener);
}
}
Do not expect it to run right the way, I am giving only ideas, you have to look and see if it fit for you are looking for.

I have 200 textviews and i want to know which one was pressed then how to change the text

I have a problem... have been thinking about it for a while now and been looking on line and still haven't come up with a clear explanation...
I have a number of textviews and have set onClickListeners to each of them.. and when the user clicks on one of them I want them to have the ability to change the text to another set of string array options which I have created progammatically. When the user selects an option the text should change to the option they choose. (I.e. TextView was A now it is B. hope this makes sense.. anyway... )
The current solution was to set a OnClickListener to every TextView and when someone pressed it an individual dialog showed. But I found that if I do this the code would be so long it would take an eternity to code so am hoping someone has a more elegant way of coding such a long process =(
So I guess my question would be... 1) is there a way I can find out which text view was pressed and then change the text of that TextView being pressed within a single method? to save me having to code 1000 alert dialogs...
http://i.stack.imgur.com/LRJGz.png
I would advise you to use a grid view.
You can see which textview was pressed like this:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
//get id
switch (v.getId()) {
case R.id.textView1: ...
}
});
One of the ways to do what you want is to use the text view setTag() and getTag() methods.
On init of a text view use the setTag() to set some value to identify the view.
In the on click event use the getTag() on the view argument to know which view was clicked.
I would suggest holding the textviews in an array, like so:
TextView[] textViewArray = new TextView[textViewCount];
Then using a for loop assign each one a tag of integer - it's position
textViewArray.setTag(i)
And add an onClickListener to each one, again using a for loop:
textviewArray[i].setOnClickListener(etc...)
Then when one is clicked, you can use get the position of view that was clicked. This will require a custom method inside of your:
textviewArray.setOnClickListener(new customOnClickListener())
Where your customOnClickListner is like this:
private class customOnClickListener implements CompoundButton.{
public void OnClick(View view){
int position = (Integer) view.getTag()
///Do more code here - your processing
}
}
Hope that makes sense :)
For your for loops, you could use for(i = 0, i
Use set id for all text, where set the id positive integer(distinct), and then have one on view click listener(set it all) where u catch all text view clicks(downcast view with textview) and in side it put a switch case where you handle clicks on which text view is clicked.
You have to set "onClickListner" on all of of your textview.
For Saving some length of code i would suggest you create a function of your dialogbox, and give some int parameter to it, which would be directly called by the clickListener of textview,
Like ,
int i=0;
......
textView1 = (TextView)findViewById(R.id.yourtextview1);
textView2 = (TextView)findViewById(R.id.yourtextview2);
......
......
// and so on, for your all textviews
#Override
public void onClick(View view) {
if (view.equals(textView1)) {
i = 1;
CustomDialog(i);
}
//Similarly for all your textViews..
..........
Make A function CustomDialog Like
public void CustomDialog(int i){
if(i==1){
//Do something
}
}

How can I change Text of Textview from other funcion?

this is my first question so I hope to make it clear.
I have one textView with some numerical text and next to it one button with one click listener and what I want is that when you click on the button the numerical value (>=0) of the TextView decrements in one.
Here is part of my code:
TextView Counter = new TextView(this);
if (intSeries != 0)
Counter.setText(Integer.toString(intSeries));
else
Counter.setText("0");
Counter.setId(4);
tablaContador.addView(Counter,Tr);
Button Done = new Button(this);
Done.setText("-1");
if (intSeries != 0)
Done.setVisibility(View.VISIBLE);
else
Done.setVisibility(View.GONE);
Done.setId(6);
Done.setOnClickListener(this);
And this is the onClick funcion (part of it):
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case 6:{
TextView text = (TextView)findViewById(4);
int series = Integer.parseInt(text.getText().toString());
series--;
text.setText(series);
if (series==0){
Button boton = (Button)findViewById(6);
boton.setVisibility(View.GONE);
}
}
}
}
The error is when I try to make the setText inside the onClick function, I hope it can be fixed or maybe recieve other idea to do it.
Thank you so much.
I would avoid all this hardcoding of Ids, use resources instead.
Your call to
text.setText(series)
is passing an int. The only valid setText(int resId) overload expects a resource associated with the int value, i.e. a string resource.
Convert your series value to a string.
Something like:
text.setText(Integer.toString(series));
You should setup series as an integer. And increase/descrease it as you wish. When you want to change the button's text convert the int to String.
Instead of:
text.setText(series);
use:
text.setText(String.valueOf(series));
Variablenames in java can't start with a capital letter. That is reserved for classnames.
Counter -> counter
Done -> done
I tried this and it worked:
//Create onClickListener
OnClickListener pickChoice = new OnClickListener()
{
public void onClick(View v)
{
TextView txt = (TextView) findViewById(4);
int number = Integer.valueOf(txt.getText().toString());
txt.setText(String.valueOf(number -1));
}
};
//Create layout
LinearLayout lnLayout = new LinearLayout(this);
lnLayout.setOrientation(LinearLayout.VERTICAL);
TextView txt = new TextView(this);
txt.setId(4);
txt.setText("0");
lnLayout.addView(txt);
Button Done = new Button(this);
Done.setText("-1");
Done.setId(6);
Done.setOnClickListener(pickChoice);
lnLayout.addView(Done);
setContentView(lnLayout);
Where are you creating your button inside? an activity? the part where you pass the onClickListener to the button doesn't make sense, maybe the button is getting a wrong listener and gets you an error every time you press the button ?
The code should be easy to understand, if there is anything you need me to explain please ask :)

How to create another button in android dynamically

As the title states, I am looking to find out how to create a button dynamically when another button in another activity is pressed. This is being done with the Android SDK.
Basically, I have two activities, MainActivity and SecondaryActivity, within the SecondaryActivity you enter some information, title, text, id, so on and so forth. When you click the "Save" button it sends some, information to MainActivity(not the issue). As well as sending the information, I need to create an entirely new button within the MainActivity.
Any suggestions on how this should be accomplished?
Thanks.
Edit 1
public void CreateNewButton(View view)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
TextView newTextView = new TextView(this);
int id = rand.nextInt(100);
int newId;
newTextView.setVisibility(View.VISIBLE);
newTextView.setId( R.id.new_button + id );
newTextView.setText("New Item");
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(getBaseContext(), SecondActivity.class);
startActivity(intent);
}
});
lineLayout.addView(newTextView);
}
This code generates the new TextView( Decided to change it up ) but now the issue I have, is newTextView.setText(); needs to get the text from the other activity
newTextView.setText(i.getData().toString());
putting this in the CreateNewButton(View view) methods causes an error since technically there is no data in the field that it is trying to grab from.
The problem at hand is I need to create the new TextView field WITH the name of the new account that has yet to be created. If that makes any sense.
I'm going to assume you want to add this button to a LinearLayout:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
Button button = new Button(this);
button.setText("I'm a button!");
// add whatever other attributes you want to the button
linearLayout.addView(button);

Android : get the id of dynamically generated ImageButton when clicked

I have dynamically generated ImageButtons with different ImageResource for each ImageButton. Now I want to know which ImageButton was clicked, how can I determine this ?
Need your help.
Thanks.
you can set an id for each created ImageButton and getId() for check witch button clicked
ImageButton im=new ImageButton(Yourcontext);
im.setId(giveAnID);
//where you check
int theID=im.getId();
In order to do this you could do two things:
Firstly, when dynamically generated the ImageButton you could call setId() in order to set a specific id to this View and store it in List, etc.
Then when you have a click event (or anything else), you can call the getId() method of the View to get the id.
Then you can compare and do anything you want.
Hope this helps!
Any resource is uniquely identified by its id which is generated in R.java file.
So you can use something like :
if(image.getId() == R.id.image) {
// do awesome stuff
}
If your code generates the imageButtons then, in this code you can write something like,
imageButton.setId(1);
and when your imageButton is clicked then you can get it with,
int id = imageButton.getId();
i had to do same thing and this is what i have done
for(int i = 0 ;i<mediaList.size();i++){
view_media_gallery_item = LayoutInflater.from(view.getContext()).inflate(R.layout.e_media_gallery_item, null);
TextView title = (TextView) view_media_gallery_item.findViewById(R.id.media_gallery_item_title);
TextView subtitle = (TextView) view_media_gallery_item.findViewById(R.id.media_gallery_item_subtitle);
ImageView flux_Title_Image =(ImageView) view_media_gallery_item.findViewById(R.id.media_gallery_item_img);
title.setId(i+100);
subtitle.setId(i+1000);
flux_Title_Image.setId(2000+i);
title.setText("" +mediaList.get(i).getTitle());
subtitle.setText(""+mediaList.get(i).getArtist());
System.out.println("view added::::");
view_media_gallery_item.setTag(mediaList.get(i));
view_media_gallery_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("view media clicked");
Media m = (Media )v.getTag();
medialistner.setOnItemclick(m);
}
});

Categories

Resources