2017-02-07 49 views
1

我有一個EditText,當輸入任何數字時,$符號應該基於字符串輸入移動。例如,如果我輸入20,$符號應該向右移動,它應該是20 $。如果我輸入200,$符號應該向右移動,它應該是200 $。任何幫助將不勝感激。

這是我的代碼看起來是截至目前:`

<EditText 
android:id="@+id/amount_edit_text" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_marginTop="@dimen/space_normal" 
app1:inputTextSize="@dimen/text_large" 
app1:inputIconDrawable="@drawable/ic_dollar_sign" 
app1:inputIconTint="@color/colorDark" 
app1:inputOneHint="@string/offer_amount"    
app1:inputIconTranslateY="@dimen/offer_large_text_icon_shift" 
app1:inputType="number"/> 

`

+1

那你試試? http://stackoverflow.com/help/how-to-ask – PaulProgrammer

+0

只是一個語義問題,但不是美元符號通常駐留在數字的左側?例如$ 200 – RayfenWindspear

+0

@RayfenWindspear:是的,但是,將它放在正確的位置就是要求。 – user1903022

回答

1

您可以使用TextView.addTextChangedListener()觀看文本更改時。然後,您可以只需將$添加到任何地方。

編輯:正如Cruncher指出的,這可能會觸發另一個onTextChanged事件。所以把它包裝在一個if中,檢查它是否已經以$結尾。

事情是這樣的:

EditText amountEditText = (EditText) findViewById(R.id.amount_edit_text); 
amountEditText.addTextChangedListener(new TextWatcher() { 

    public void afterTextChanged(Editable s) { 
    } 

    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
    } 

    public void onTextChanged(CharSequence s, int start, int before, int count) { 
     // add $ only if we need to 
     if (!s.toString().substring(s.length() - 1)).equals("$")) { 
      amountEditText.setText(s + "$"); 
     } 
    } 
}); 
1

隨着addTextChangedListener(TextWatcher watcher)添加TextwatcherEditText

實現TextWatcher.onTextChanged(CharSequence s, int start, int before, int count)這樣的:

TextWatcher.onTextChanged(CharSequence s, int start, int before, int count){ EditText.setText(s + "$"); }

+0

嗯,不改變textwatcher觸發另一個onTextChanged文本? – Cruncher