TextView set multiple string into a setText(int resid) - android

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

Related

Passing a value via Button ( maybe hidden)

This code was working until last night, but now now. I'm wanting a value to be record that is linked to the buttons, I have used set and get tag but is only returning last value.
//create a layout
LinearLayout layout = (LinearLayout)findViewById(R.id.linearlayout);
// create a list of buttons
for(x=0; x<3; x++)
{
newBut = new Button(this);
newBut.setText("("TEXT");
newBut.setTextColor(Color.parseColor("#FFFFFF"));
newBut.setTag(x); //hide job id within the button.
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(newBut.getTag().toString());
System.out.println(newValue); //this just a test to display the value
}
});
layout.addView(newBut);
}
Is the error obvious - not to me.
It is returning the last value, because in all the created listeners you always reference the same button (last value of newBut variable), ignoring the actual click source view you have as the argument. Is should be:
newBut.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int newValue = Integer.parseInt(v.getTag().toString());
System.out.println(newValue);
}
});

adding values put in by users

i am trying to write some sort of code, which adds two numbers the user puts in, this is my code:
l.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i= Integer.parseInt(l.input1.getText().toString());
int j= Integer.parseInt(l.input2.getText().toString());
int sum = i+j;
l.result.setText(sum);
}
});
for some reason the emulator just collapse, i am new to this all, and am really greatfull for any help. THANK YOU.
setText() of TextView either accepts a String value as parameter to display or a integer value which is a string resource id that you have described in res/values/strings.xml
The integer value you passing is a real value and you have make the TextView to understand it as real value and not a String resource reference. So convert the integer to String and then set the value inside text view.
Solution:
l.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i= Integer.parseInt(l.input1.getText().toString());
int j= Integer.parseInt(l.input2.getText().toString());
int sum = i+j;
l.result.setText(String.valueOf(sum));
}
});

Changing Imageview on button dynamically

In my application, I have button and ImageView.
Here when i press button i want to change ImageView. I have 5 images in my drawable folder. On press button ImageView changes images one by one based on button click. I want it's solution.
Grateful to anyone that can help.
Maintain an array of image ids and inside onClick, set images using id from the array, then increment index.
Eg:-
ArrayList<Integer> ids=new ArrayList<Integer>();
ids.add(R.drawable.image1);
ids.add(R.drawable.image2);
ids.add(R.drawable.image3);
ids.add(R.drawable.image4);
ids.add(R.drawable.image5);
Int index=0
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(index<ids.size()){
imageview.setImageResource(ids.get(index));
index++;
}
else index=0;
}
});
As #Nizam said just maintain an array of id and load dinamically the image in the onClick(). Instead of the Random use a field variable and increment it. Be careful to the array length!
final int[] ids = new int[] { R.drawable.img1, R.drawable.img2 };
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int randomId = new Random().nextInt(ids.length);
ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setImageDrawable(getResources().getDrawable(randomId));
}
});

TextView onclickListener

In my application i have added textviews dynamically using array,and given id's for each with a count variable, which increment's count according to the addition of textviews.In onClickListener of each textview i want to perform some oparations,but when i'm trying to do this operation is getting performed on all textviews.
Below is the code,i'm not getting what's wrong.please help me.
// here i have added textview dynamically
mtxtview[colTextCount]=new TextView(this);
mtxtview[colTextCount].setId(colTextCount);
mtxtview[colTextCount].setLayoutParams(new LayoutParams(20,20));
And In onclickListener-
#Override
public void onClick(View v) {
System.out.println("onclick...");
for(jj=0;jj<_mTextViewId;jj++){
String hh=mtxtview[jj].getText().toString();
System.out.println("................................."+hh);
System.out.println("id is...."+_mTextHeight[jj].getId());
//if i added 3 textview.its giving me all 3 textview's text(getText())
}
}
use switch-case and View.getId() to check which TextView is Clicked before starting for loop . try it as :
#Override
public void onClick(View v) {
System.out.println("onclick...");
switch(v.getId())
{
case _mTextViewId:
for(jj=0;jj<_mTextViewId;jj++){
String hh=mtxtview[jj].getText().toString();
System.out.println("................................."+hh);
System.out.println("id is...."+_mTextHeight[jj].getId());
}
break ;
// same for others....
}
}
see TextView onClick() not working
You should do setOnClickListener for each TextView Object.

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