2016-12-15 59 views
2

我試圖綁定:Android的數據綁定浮到TextView的

@Bindable 
public float getRoundInEditAmount() 
{ 
    return roundInEdit.getAmount(); 
} 

@Bindable 
public void setRoundInEditAmount(float amount) 
{ 
    roundInEdit.setAmount(amount); 
    notifyPropertyChanged(BR.roundInEditAmount); 
} 

<EditText 
      android:layout_width="100dp" 
      android:layout_height="50dp" 
      android:inputType="numberDecimal" 
      android:text="@={`` + weightSet.roundInEditAmount}" 
      ></EditText> 

然而在點擊我提出了一個文本輸入沒有數字鍵盤的EditText。如果我再次點擊這個EditText,我會看到數字鍵盤。如果該字段默認爲50.0或其他值,我不能刪除這些金額。我可以輸入文字,但它仍然存在。

有沒有其他人遇到過這種行爲,文本輸入是在第一次點擊而不是數字鍵盤上出現的? EditText上的雙向綁定也按照我期望的方式工作。我已經編寫了自己的Binding和InverseBinding適配器,它們的行爲方式相同 - >首先點擊TextInput,然後點擊第二次點擊,但不能刪除開始的數字。

+0

你能解釋爲什麼你需要第一次點擊textpad輸入和第二次點擊numberpad? –

+0

如果你閱讀這個問題,你會發現這不是必需的,而是實際的行爲。 – Luthervd

+0

嗨,roundInEdit是什麼類型的變量 –

回答

0

嘗試這樣

<EditText 
      android:layout_width="100dp" 
      android:layout_height="50dp" 
      android:inputType="numberDecimal" 
      android:text="@={String.valueOf(weightSet.roundInEditAmount)}"/> 
3

如果你使用Android數據綁定庫,它解決了創建binding adapter

public class BindingUtils { 

    @BindingAdapter("android:text") 
    public static void setFloat(TextView view, float value) { 
     if (Float.isNaN(value)) view.setText(""); 
     else view.setText(... you custom formatting); 
    } 

    @InverseBindingAdapter(attribute = "android:text") 
    public static float getFloat(TextView view) { 
     String num = view.getText().toString(); 
     if(num.isEmpty()) return 0.0F; 
     try { 
      return Float.parseFloat(num); 
     } catch (NumberFormatException e) { 
      return 0.0F; 
     } 
    } 
}