Reputation: 381
I am working on an app where the user inserts his/her name and i will be displayed in a textview.
package com.opgaveet.buttonlistener;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText edit;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button1);
edit = (EditText) findViewById(R.id.editText1);
text = (TextView) findViewById(R.id.textView2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Your name has been submitted", Toast.LENGTH_LONG).show();
String name = edit.getText().toString();
text.append(name);
}
});
}
@Override
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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This code work fine, no issues there, but it only displays the name that has been inserted. Is there a method to also display "Welcome name inserted" instead of just the name, when the name has been submitted?
Upvotes: 0
Views: 2127
Reputation: 2609
TO append data of same textview. Create a textview and string like this.
String: <string name="welcome">Welcome</string>
Textview
android:id="@+id/text"
android:text="@string/welcome"
In Activity set like this.
txt_welcome = (TextView)findViewById(R.id.text);
txt_welcome.setText(txt_welcome.getText().toString()+" "+USERNAME);
Upvotes: 1
Reputation: 1580
Use:
String name = "Welcome " + edit.getText().toString();`
or:
text.append("Welcome" + name);`
Upvotes: 2
Reputation: 3555
What you'll want to do is use a string in your strings.xml file with a marker in that string which will be replaced.
Create a string in your strings.xml file:
<string name="welcome_text">Welcome %s inserted</string>
Now in your code do this:
text.append(String.format(getString(R.string.welcome_text), name);
You can also just do
getString(getString(R.string.welcome_text), name);
More info here: http://developer.android.com/reference/java/util/Formatter.html
Upvotes: 2
Reputation: 961
You could simply concatenate the "Welcome" part, something like this:
text.append("Welcome " + name);
Upvotes: 3