Getting specific text to show up in textview - android

This has been bugging me, I'm a beginner and can't seem to figure this out. Here's my code:
package com.example.imhungry;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class ImHungry extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_im_hungry);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_im_hungry, menu);
return true;
}
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordList[] = new String[9];
{
wordList[0] = "Mexican";
wordList[1] = "American";
wordList[2] = "Barbeque";
wordList[3] = "Chinese";
wordList[4] = "Indian";
wordList[5] = "Italian";
wordList[6] = "Thai";
wordList[7] = "Viatnamese";
wordList[8] = "Middle Eastern";
}
String wordToDisplay = wordList[randomInt];
}
Basically I am attempting to make the wordToDisplay show up in my textView but I cannot figure out how to do so.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text=""
tools:context=".ImHungry" />
Also, sorry for asking so many questions, i'm new at this. Thanks!

To make your test appear in TextView you have to set it with setText();, so basically you have to assign your textview id or tag (add android:id="#+id/mytextview) then get that object TextView tv = (TextView)findViewById(R.id.mytextview); tv.setText("foo"); I'd also recommend going through some tutorials on android basics - will help

Add id to the TextView:
<TextView
android:id="#+id/text_random_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text=""
tools:context=".ImHungry" />
In the code do the next:
Add just after the button:
final TextView textView = (TextView) findViewById(R.id.text_random_text);
Set the wordToDisplay to the text in the onClick(View v) method
textView.setText(wordToDisplay);

For efficiency try this:
public class ImHungry extends Activity {
Random mRandomGenerator = new Random();
TextView mTextView;
String mWordList[] = new String[] {
"Mexican", "American", "Barbeque",
"Chinese", "Indian", "Italian",
"Thai", "Viatnamese", "Middle Eastern" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_im_hungry);
mTextView = (TextView) findViewById(R.id.textView);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
mTextView.setText(mWordList[mRandomGenerator.nextInt(9)]);
}
});
}
}
You can remove the rest of the code.
You only need to create one random number object and you don't need to save the random Integer or corresponding String in local variables, if you only use them once. However it is okay to save them in local variables if you want to improve readability.

Related

When I close my app, all the dynamically generated content is gone, so how can I save the generated content?

Does anyone have any idea how I can save the dynamically generated Textviews? So, the next time I open the app, the TextViews will display the same content that I previously put into them.
I have looked into onSaveInstanceState, onRestoreInstanceState but None of them work. Are there any libraries I can use to save generated TextViews? Or maybe any advice on a better method of doing this. I've researched this stuff for a couple of days and have found outdated information and information that doesn't seem relevant to me. Code solutions will be very much appreciated
MainActivity.java:
package com.example.savingdynamiccontent;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private LinearLayout mLayout;
private LinearLayout ListItems;
static final String counter_value = "int_value";
static final String toDoList_value = "toDolist";
private EditText mEditText;
private Button mButton;
private int counter;
private ArrayList<String> toDoList;
private ArrayList<String> keys;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (toDoList != null){
System.out.println("Success!");
for(int i = 0; i< toDoList.size(); i++){
System.out.println(toDoList.get(i));
ListItems.addView(createNewTextView(toDoList.get(i)));
}
}
else{
System.out.println("Nope!");
toDoList = new ArrayList<String>();
}
counter = 1;
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
ListItems = (LinearLayout) findViewById(R.id.listItems);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
}
private View.OnClickListener onClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
ListItems.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
private TextView createNewTextView(String text) {
final RadioGroup.LayoutParams lparams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setFreezesText(true);
textView.setText(counter + ":" + text);
textView.setId(counter);
System.out.println(textView.getId());
toDoList.add(text);
counter++;
return textView;
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(counter_value);
toDoList = savedInstanceState.getStringArrayList("key");
// Add this for-loop to restoring your list
for(String str : toDoList){
ListItems.addView(createNewTextView(str));
}
//REad values from the savedInstanceState" -object and put them in your textview
}
#Override
protected void onSaveInstanceState(Bundle outState){
// Save the values you need from your textview into "outSTate" -object
// outState.putParcelableArrayList("key", toDoList);
outState.putInt(counter_value, counter);
outState.putStringArrayList("key", toDoList);
super.onSaveInstanceState(outState);
}
}
Activit_Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/listItems"></LinearLayout>
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+"
/>
</LinearLayout>

Creating views programmatically

I'm a new android developer and I decided to create a simple test app that has 6 editViews and calculates the average of those numbers inputted.
I am looking to find out how to create the views programmatically when needed instead of wasting resources on having all of the views there OnCreate.
I've been searching around but have been unable find out how to implement it. If someone could help out that would be great.
Thanks!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
average = (TextView)findViewById(R.id.average);
edit_message = (EditText)findViewById(R.id.edit_message);
editText = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
editText3 = (EditText)findViewById(R.id.editText3);
editText4 = (EditText)findViewById(R.id.editText4);
editText5 = (EditText)findViewById(R.id.editText5);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
s1 = edit_message.getText().toString();
s2 = editText.getText().toString();
s3 = editText2.getText().toString();
s4 = editText3.getText().toString();
s5 = editText4.getText().toString();
s6 = editText5.getText().toString();
if(!s1.isEmpty()) {
n1 = Integer.parseInt(s1);
counter++;
}
if(!s2.isEmpty()) {
n2 = Integer.parseInt(s2);
counter++;
}
if(!s3.isEmpty()) {
n3 = Integer.parseInt(s3);
counter++;
}
if(!s4.isEmpty()) {
n4 = Integer.parseInt(s4);
counter++;
}
if(!s5.isEmpty()) {
n5 = Integer.parseInt(s5);
counter++;
}
if(!s6.isEmpty()) {
n6 = Integer.parseInt(s6);
counter++;
}
if(counter>0) {
s1 = String.valueOf((n1 + n2 + n3 + n4 + n5 + n6) / counter);
average.setText(s1);
}
else {
average.setText("0");
}
counter = 0;
}
});
}
Without more details, I'll give you at least a place to start. You can instantiate TextViews programmatically and then add them to your layout.
TextView tv = new TextView(context);
parent.addView(tv);
context should be your Activity or Fragment that this text view will be apart of. The parent should be a ViewGroup in your XML layout that can have multiple children like a vertical LinearLayout. Hopefully this is enough information to guide you to better Google Searching.
EDIT
LinearLayout - Not a list layout, brain fart.
This is a sample just for reference:
The layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.test.MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="add" />
<Button
android:id="#+id/del"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="del" />
<Button
android:id="#+id/sum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sum" />
</LinearLayout>
This is the activity:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout container;
Button add;
Button del;
Button sum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
container = (LinearLayout) findViewById(R.id.container);
add = (Button) findViewById(R.id.add);
del = (Button) findViewById(R.id.del);
sum = (Button) findViewById(R.id.sum);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText edit = new EditText(MainActivity.this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
edit.setLayoutParams(params);
edit.setInputType(InputType.TYPE_CLASS_NUMBER);
container.addView(edit);
}
});
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = container.getChildCount();
if (count > 0)
container.removeViewAt(count - 1);
}
});
sum.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = container.getChildCount();
int sum = 0;
for (int i = 0; i < count; i++) {
EditText edit = (EditText) container.getChildAt(i);
String numStr = edit.getText().toString();
if (numStr == null || !(numStr.length() > 0)) {
sum += 0;
} else {
sum += Integer.parseInt(numStr);
}
}
Log.i("Test", "sum = " + sum + " avg = " + (sum * 1.0f / count));
}
});
}
}

Simple Math Android App Not Working

I am new to Android developing and I am trying to make a simple app as practice. All it consists of is you type one number into the first box, a number into the second box, press a button and the result prints into a textview. The problem is, when I press the send button Nothing is happening. Eclipse is not showing any errors, nor is LogCat. So I am officially stumped as to why when I run this I'm not getting anything out. Hopefully you guys can help.
Here is the XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="172dp"
android:orientation="vertical" >
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="48dp"
android:text="First Number:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="40dp"
android:text="Second Number:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignTop="#+id/textView1"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView2"
android:layout_toRightOf="#+id/linearLayout1"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editText2"
android:layout_below="#+id/editText2"
android:text="Calc" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
And here is the Java:
package com.example.mathbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void main(String[] args){
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {}
});}}
You are parsing the wrong string..
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
What you are doing now is parsing the strings "num1" and "num2" into a string and I don't think that is what you want. So it should be:
int x = Integer.parseInt(num1.getText().toString());
int y = Integer.parseInt(num2.getText().toString());
And also move the code into the onCreate() method just like #AndroidEnthusiastic suggested.
public void main(String[] args)
For Android it is a simple method,not an entry point that by the way supposed to be :
public static void main(String[] args)
I can't see that you are calling your main method in your code.
num1.getText().toString();
num2.getText().toString();
You just get the values without assigning it to any properties.
This code is totally wrong.
I suggest you to start from the beginning with official Android Training : Building Your First App.
Hye Diamond you are doing something wrong. Its ok your beginner. see you are creating main mothod. In java main method public static void main get executed first but here once activity created oncreate method will execute. So you can do it in following ways:
//inside oncreate method do like this
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int val1 = num1.getText().toString();
int val2 = num2.getText().toString();
int x =Integer.parseInt(val1);
int y =Integer.parseInt(val2);
int nas = x + y;
tv.setText(nas);
}
});
this might be help you. It's not tested. May be you have to do some changes.
Here is the complete solution
package com.example.mathbox;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
num1.getText().toString();
num2.getText().toString();
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Please take a look at this link
Find this code.. hope it helps
public class MainActivity extends Activity {
Button sum;
EditText num1, num2;
TextView tv;
String x;
String y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
sum = (Button) findViewById(R.id.button1);
sum.setOnClickListener(new clicker());
}
class clicker implements Button.OnClickListener {
public void onClick(View v) {
Integer nas;
x = num1.getText().toString();
y = num2.getText().toString();
nas = Integer.parseInt(x) + Integer.parseInt(y);
tv.setText(nas.toString());
}
}
}
Please try this code,
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class add extends Activity {
Button button1;
EditText txtbox1,txtbox2;
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtbox1= (EditText) findViewById(R.id.txtbox1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.lbl1);
txtbox2= (EditText) findViewById(R.id.txtbox2);
button1.setOnClickListener(new clicker());
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
vis = Integer.parseInt(a)+Integer.parseInt(b);
tv.setText(vis.toString());
}
}
}
Try this,
int x =Integer.valueof(""+num1.getText().toString());
int y =Integer.valueof(""+num2.getText().toString());
int nas = x + y;
tv.setText(""+String.valueof(nas));
Please refrain from using the main function. It's not really required in an activity class and also not a general practice. #AndroidEnthusiastic has given the correct code.
Added:
Since the aforementioned answer of mine was downvoted, I'll go ahead and just tell you what you've done wrong in your code(there's a lot of code in the other answers given here).
num1 = (EditText) findViewById(R.id.editText1);
num2 = (EditText) findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
num1.getText().toString();//Store this in a string say a
num2.getText().toString();//Store this in a string say b
/*you're actually the passing the literal "num1" or "num2". Something which you don't want.
Instead, pass the strings a and b instead of num1 and num2 respectively*/
int x =Integer.parseInt("num1");
int y =Integer.parseInt("num2");
int nas = x + y;
tv.setText(nas);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*You need to put the code here. i.e. You need to take the values from the
editTexts and store them in strings and finally integers when the button is clicked.*/
}
});

Android Quote app, next and back buttons

Im trying to make a simple quote app, but every time I hit my back button after my next button it will go to the next array and not backwards. Im using an int num to keep track of with quote the user is on.
here is my back button
package me.me.quote;
public class Startme extends Activity {
Random gen= new Random();
int num;
String[] quotes = new String[15];
public void next(View N){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
if(num == 5){
num =0;}
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num++]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
public void back(View B){
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num--]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);}
public void rand(View G) {
num = gen.nextInt(5);
quotes[0]= "Love is timeless";
quotes[1]= "I hate you";
quotes[2]= "arggg!";
quotes[3]= "The end is near";
quotes[4]= "Leave be";
TextView text = (TextView) findViewById(R.id.Quote);
text.setText(quotes[num]);
TextView number = (TextView) findViewById(R.id.Qn);
number.setText(""+num);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.startquotes);
TextView Dark=(TextView)findViewById(R.id.Quote);
Typeface face=Typeface.createFromAsset(getAssets(), "fonts/font1.ttf");
Dark.setTypeface(face);
}
}
//LAYOUT FILE text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:text="VISIBLE EVERY TIME"
android:visibility="visible" />
<Button
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="NEXT" >
</Button>
<Button
android:id="#+id/next"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:text="BACK" >
</Button>
</RelativeLayout>
///ACTIVITY CLASS
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
Button next;
Button back ;
TextView quoteText;
int currentSelectedQuote=0;
String[] quote={"QUOTE1","QUOTE2","QUOTE3","QUOTE4","QUOTE5",};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
quoteText=(TextView)findViewById(R.id.textView);
quoteText.setText(quote[currentSelectedQuote]);
next=(Button)findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentSelectedQuote++;
if(currentSelectedQuote == 5){
currentSelectedQuote =0;}
quoteText.setText(quote[currentSelectedQuote]);
}
});
back=(Button)findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(currentSelectedQuote==0)
{
currentSelectedQuote=4;
}
else
{
currentSelectedQuote--;
}
quoteText.setText(quote[currentSelectedQuote]);
// TODO Auto-generated method stub
}
});
}
}

How to change a TextView's text by pressing a Button

I want to change the of a TextView by pressing a Button, but don't understand how to do it properly.
This is part of my layout:
<TextView android:id="#+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
<Button android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change text!" />
And this is my activity:
public class Click extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
// ???
}
});
}
}
What should I put inside onClick() method?
According to:
http://developer.android.com/reference/android/widget/TextView.html
TextView view = (TextView) findViewById(R.id.counter);
view.setText("Do whatever");
Find the textview by id
Change the text by invoking yourTextView.setText("New text");
Refer findViewById and setText methods.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Click extends Activity {
int i=0;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
final TextView mTextView = (TextView) findViewById(R.id.counter)
mTextView.setText("hello "+i);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
i=i+1;
mTextView.setText("hello "+i);
}
});
}
}
Hope this serve your need
TextView tv = (TextView) v;
tv.setText("My new text");
Edit:
Here is your handler:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TextView tv = (TextView) v; //code corrected
TextView tv= (TextView) findViewById(R.id.counter);
tv.setText("My new text");
}
});
TextView view = (TextView) findViewById(R.id.counter);
You can do it with the setText("anything") method.
In onclick, take the object of the TextView and set the desired text like so:
tvOBJECT.setText("your text");
Java only no XML version
To make things more explicit:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Main extends Activity {
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.i = 0;
final TextView tv = new TextView(this);
tv.setText(String.format("%d", this.i));
final Button button = new Button(this);
button.setText("click me");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Main.this.i++;
tv.setText(String.format("%d", Main.this.i));
}
});
final LinearLayout linearLayout = new LinearLayout(this);
linearLayout.addView(button);
linearLayout.addView(tv);
this.setContentView(linearLayout);
}
}
Tested on Android 22.

Categories

Resources