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.
Related
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
}
}
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 :)
I have a program that has a text input and a button. When I type something into the input and press the button I want that String to be added to a String Arraylist and have that Arraylist displayed in a TextView. Right now I have a method:
public void addString(View view)
{
EditText editText = (EditText) findViewById(R.id.edit_choice);
String message = editText.getText().toString();
choices.add(message);
}
"edit-choices" is the name of the text input and "choices" is the name of the array list. First of all am I doing this correctly? Second, how to I get the text view to display the contents of "choices". Right now my TextView id is just textView1
Please keep in mind that it is not the best way to show list items in a TextView. You can do this using a ListView. Anyhow, see pseudo code below (didn't test that in Eclipse, however, it should show how it is basically going to work):
public class YourActivity extends Activity {
Vector<String> choices = new Vector<String>();
public void onCreate(Bundle ....) {
(Button) myButton = (Button) findViewById(R.id.button);
myButton.setOnClickListener(new OnClickListener() {
#Override
public boolean button.onClick() {
addString();
TextView textView = (TextView) findViewById(R.id.text_view);
String listRepresentation = "";
for (String choice : choices)
if ("".equals(listRepresentation))
listRepresentation = choice; else
listRepresentation = ", " +choice;
textView.setText(listRepresentation );
}
});
}
public void addString(View view)
{
EditText editText = (EditText) findViewById(R.id.edit_choice);
String message = editText.getText().toString();
choices.add(message);
}
}
So simply assign an OnClickListener to your button that does what you need.
The question is how you want the Text to be displayed...
Either like a list view or just as a normal text.
If you want to show the text as a normal text in the text view you can simply do something like this.
for(String msg : choices)
{
textView1.setText(textView1.getText()+msg);
}
If you want the choices to be displayed in list view you need to set an adapter to the list view using the choices that you have.
First of all am I doing this correctly?
If it works for you, sure. I would maybe cache the EditText so you don't have to "find" it every time you want to access it's content.
Your only "problem" here is, that a TextView has no method that accepts a List<String>. So, you'll need to make a single string out of your list of strings.
You can simply iterate over the list and con-cat them together:
StringBuilder b = new StringBuilder();
for (String s : choices){
b.append(s+"\n");
}
textview.setText(b.toString());
This will simply build one string from all the items in your list, adding line-breaks after every item.
You'll need to set your TextView's android:inputType-attribute to textMultiLine, so it will actually show you multiple lines.
I have a looong text in TextView in ScrollView and I want to make a function to tab on text and select current paragraph to add it in bookmarks, but I haven't any ideas how to do it, please somebody help me. I'm trying to get current positions, but I don't know how to slect text.
You can just use new TextView for each paragraph, and let it impliment a click Listener
the code should look like this
#Override
public void onCreate(Bubdle bundle) {
super.onCreate(bundle);
ScrollView view = (ScrollView) findViewById(R.id.scrollView);
// String txt = getText from Somewhere
String[] text = txt.split(".");
for (String t : text) {
TextView view = new TextView();
view.setText(t);
view.setOnClickListener(clickListener);
view.addView(view);
}
}
with this code, my program just force close(error)
***public View x = findViewById(R.string.nfoname);***
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
//edittext
***final EditText infoname=(EditText)findViewById(R.id.infoname);***
//clear,confirm
Button clear = (Button)findViewById(R.id.buttonclear);
Button confirm = (Button)findViewById(R.id.buttonconfirm);
//clear button
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
infoname.setText("");
}
});
//confirm button
confirm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
***x=(View) infoname.getText();***
}
});
}
the one with the * are the source of error
program function:
if the user clicks confirm, his name will be set to R.string.nfoname
which will then be used in another layout through TextView x = setText(R.string.nfoname);
I am not sure that you can save text to the R.string. This is a generated class that the compiler creates for you. It gets packaged with your apk. Think of the resources as a means of translation and to present text to the screen.
I think what you would want to do is save the user input as a SharedPreference or in a database.
See:SharedPreferences on the android docs for an example usage.
At least in the case of your variable infoname scoping is most likely causing your application to throw an error. infoname is a local variable to the function onCreate(), not an instance variable for your class, so it can't be accessed by your onClick() methods because they are part of an anonymous class.
Another thing I'd question is why you marked infoname as final? It goes out of scope when onCreate() exits so if it gets changed, you can see who changed it since it only exists while the method is executing.
You cannot set values to R.string.xxx because all these values will be constants much like a read only stuff. If you want to use the value of edit text to another layout use class variables or intent.putextra()
Coming to ur source code i see this
public View x = findViewById(R.string.nfoname);
How can a view be found by R.String? This should be R.id.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Why this editText has to be final?
***x=(View) infoname.getText();***
You just use infoname.getText().toString() you will get the string value of the Edittext's current text.
Dude you can do stuff simply.
public View x = findViewById(R.string.nfoname);
This can't work as not only are you trying to find a View using a R.string resource id, you are doing it before setContenView(...) is called in your onCreate(...) method. Even if you used a valid View resource id such as R.id.infoname then x will be null because the content view hasn't been inflated yet.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Apart from the pointless use of final this should'nt cause problems as long as R.id.infoname is actually the resource id of an EditText.
x=(View) infoname.getText();
Not only will x be null but calling getText() on an EditText returns an Editable which is not a View nor is it possible to cast it to View. Even if you used getText().toString() which is the correct way to get the text from an EditText it still wouldn't be possible to cast a String to a View.
Also, as for this...
TextView x = setText(R.string.nfoname);
It would have to be...
TextView x = (TextView) findViewById(<some id>);
x.setText(getString(R.string.nfoname));