2014-09-25 58 views
0

我正在使用用戶插入他/她的名字的應用程序,並且我將顯示在textview中。帶有靜態字符串的Android編輯文本

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); 
    } 
} 

此代碼正常工作,沒有問題,但它只顯示已插入的名稱。當名稱被提交時,是否還有一種方法可以顯示「Welcome 名稱插入」,而不僅僅是名稱?

回答

3

你可以簡單地串聯了「歡迎」的一部分,是這樣的:

text.append("Welcome " + name); 
+0

非常感謝幫助= D! – Santelices 2014-09-25 23:18:27

+0

不客氣;) – kevinkl3 2014-09-25 23:21:12

2

什麼你想要做的就是在strings.xml文件中該字符串將使用字符串用記號筆被替換。

在strings.xml文件中創建一個字符串:

<string name="welcome_text">Welcome %s inserted</string> 
在你的代碼

現在這樣做:

text.append(String.format(getString(R.string.welcome_text), name); 

你也可以這樣做

getString(getString(R.string.welcome_text), name); 

更多信息在這裏: http://developer.android.com/reference/java/util/Formatter.html

2

用途:

String name = "Welcome " + edit.getText().toString();` 

或:

text.append("Welcome" + name);` 
1

追加相同的TextView的數據。像這樣創建一個textview和字符串。

字符串:<string name="welcome">Welcome</string>

的TextView

android:id="@+id/text" 
android:text="@string/welcome" 

活動組這樣的。

txt_welcome = (TextView)findViewById(R.id.text); 
txt_welcome.setText(txt_welcome.getText().toString()+" "+USERNAME); 
相關問題