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 :)
Related
In my activity I have the following views
TextView player1;
TextView player2;
TextView player3;
TextView player4;
EditText player1name;
EditText player2name;
EditText player3name;
EditText player4name;
Each of the TextView's has the onclick listener applied to it. and so fires the OnClick function.
When we get to the onClick this is what i am currently doing:
#Override
public void onClick(View v) {
//the v variable is the clicked textview, in this case "player1"
//hide the textview and show the resultant edittext
v.setVisibility(View.GONE);
player1name.setVisibility(View.VISIBLE);
//set focus on edit text and when focus is lost hide it and set the textview text
player1name.requestFocus();
imm.showSoftInput(player1name, InputMethodManager.SHOW_FORCED);
player1name.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View y, boolean x) {
v.setVisibility(View.VISIBLE);
player1name.setVisibility(View.GONE);
imm.hideSoftInputFromWindow(player1name.getWindowToken(), 0);
String name = player1name.getText().toString();
if (name.equals("")) {
v.setText("Player Name1");
} else {
v.setText(name);
}
}
});
}
However with this solution I will need to duplicate this code and change the view names for player2 - player2name, player3 - player3name etc
i can obviously grab the clicked TextView via v, however what i cant seem to do is grab its corresponding EditText.
i had thought of doing this:
View test = v + "name";
//then i replace all references to player1name with the test variable
but it doesnt work it wants me to convert View test; into a string
any suggestions?
EDIT: made it easier to understand my question
View test = v + "name";
will give a compile error. Because "v" is not a string type. and also even if it was String, test is not. This line is pretty wrong.
There a few options to achieve what you want,
You can use hashmap
Declare a global field for hashmap
private final HashMap<Integer,EditText> map = new HashMap<Integer,EditText>();
and in onCreate method put your textview id as key, and put your edittext variables in value.
player1name = (EditText) findViewById(R.id.player1name);
map.put(R.id.textView1, player1name);
// for the rest
in onClick method
EditText e = map.get(v.getId());
Then replace them with "e"
e.requestFocus(); //example
Will you please state your problem clearly? Currently, your language is very ambiguous and I can not figure out, exactly what are you looking for. It will help us to know your problem and in turn solve it.
Currently i am having some problem with implementing onclicklistener to a dynamically creating textview. I will explain the problem more detailed. What i need to do is, i need to create textviews when i click a button in an activity and when i click on that textview it should get removed. but i am not able to set onclicklistener to each textview. Since, set onclicklistener of textviews are written inside the onclick function of the above said button(button used for creating the textview), its scope get over when it exits from onclick function of the button(i think this is the problem). So i tried using visible and invisible feature, which will create the textviews before hand and make them invisible and they are made visible only when the button(button used for creating the textview)is clicked. But here even though it is invisible the space will be allocated(ie, blank space will be availabe).
Here is my code
This button addphone will dynamically create textview by inserting the value present in the edittext phoneno
addphone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(phoneno.getText().toString().length() > 0 && counter < MAX)
{
addphoneno[counter] = phoneno.getText().toString();
phoneno.setText("");
final TextView mybox = new TextView(getApplicationContext());
mybox.setText(addphoneno[counter]);
mybox.setPadding(5, 5, 5, 5);
mybox.setBackgroundColor(Color.rgb(99, 99, 99));
contactbox[counter] = mybox;
contactbox[counter].setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
contactbox[counter].setId(100+counter);
contactbox[counter].setText(addphoneno[counter]+" "+"X");
contactbox[counter].setClickable(true);
contactbox[counter].setOnClickListener(this); //This doesn't work!!!!!
counter = counter+1;
}
}
});
But the setOnClickListener in the above line is not working
So can anyone pls help me with this problem. I hope you are clear with my question.
Thank You!
You can try this:
private OnClickListener phoneViewClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// your code
}
};
and use that listener in your TextViews:
contactbox[counter].setOnClickListener(phoneViewClickListener);
You will have to actually define a onClickListener instead of simply setting it as a boolean value.
contactbox[counter].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//this is where you would handle your click event
}
});
Good luck!
If your button was defined on the xml layout you can do that.
In your xml layout you can define which method will be called when a user click on your button:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/add_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="addTextView" /> // This is most imporant line
Your activity must have a method with the same name with a View parameter, like that:
/** Called when the user touches the button */
public void addTextView(View view) {
// Do something in response to button click
if(phoneno.getText().toString().length() > 0 && counter < MAX)
{
addphoneno[counter] = phoneno.getText().toString();
phoneno.setText("");
final TextView mybox = new TextView(getApplicationContext());
mybox.setText(addphoneno[counter]);
mybox.setPadding(5, 5, 5, 5);
mybox.setBackgroundColor(Color.rgb(99, 99, 99));
contactbox[counter] = mybox;
contactbox[counter].setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
contactbox[counter].setId(100+counter);
contactbox[counter].setText(addphoneno[counter]+" "+"X");
contactbox[counter].setClickable(true);
contactbox[counter].setOnClickListener(this); //This will work \o/
counter = counter+1;
}
}
}
On this method you should put your code to addViews.
As the behavior of all added textview must to be the same( i understood in that way), be removed when a user clicked on it, you can make your activity implements onClickListener and with that you just need to implement correctly the onClick method of your activity.
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.
I have just started learning Android and got some misunderstanding. I'm trying to create an application which displays a textView and a button. Every button click generates a new random number which should be displayed in the textView.
But unfortunately my code causes a list of errors. Here it is:
public class FirstAndroidProjectActivity extends Activity {
public OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
Random r = new Random();
int i = r.nextInt(101);
tv.setText(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(listener);
}
}
If I just don't use random and use some string except of i
(for example tv.setText("99");) everything is ok, but it doesn't work with a variable as a parameter of setText().
Where is a mistake?
Hope for your help.
You need to convert your random number to a string before setting the text on your TextView
Try
tv.setText(i +"");
Try:
tv.setText(String.valueOf(i));
Java doesn't auto convert types. The + operator is overloaded to transform the parameters passed to it into a String when one or more of those paramaters is a String. So, when you pass i + "" to setText() you are passing a String, however if you just pass i then the compiler sees you passing an int to a method that expects a String and lets you know that that can't be done.
i is an int, try tv.setText("" + i);
Convert your integer to a String before setting it to the textView. You should also move Random r = new Random(); outside of the method, or else your numbers may not really be random :
Random r = new Random();
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.display);
int i = r.nextInt(101);
tv.setText(Integer.toString(i));
}
From the documentation :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers
If you create two Random objects too quickly (for example the user clicks two times on the button very quickly), they will share the same seed (the system clock is used to generate it) and as a result you will get the same number two times.
By creating only one Random instance in a global variable, you avoid this issue.
use
tv.setText(new Integer(i).toString()) ;
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);
}
});