2017-02-10 8 views
1

별도의 클래스를 사용하여 통화 형식의 서식을 다시 사용하려고하면 오류가 발생합니다.System.InvalidCastException : 지정된 캐스트가 editText.AddTextChangedListener에서 유효하지 않습니다.

메인 루틴 :

System.InvalidCastException: Specified cast is not valid on editText.AddTextChangedListener

: 코드가 실행되면 포맷 ( Better way to Format Currency Input editText?)

using Android.Widget; 
using Android.Text; 
using Java.Lang; 
using System; 
using Java.Text; 
using Java.Util; 
using System.Text.RegularExpressions; 

namespace TextWatcher 
{ 

    public class CurrencyTextWatcher : ITextWatcher 
    { 
     private EditText editText; 
     private string lastAmount = ""; 
     private int lastCursorPosition = -1; 

     public CurrencyTextWatcher(EditText txt) 
     { 
      this.editText = txt; 
     } 

     public IntPtr Handle 
     { 
      get 
      { 
       throw new NotImplementedException(); 
      } 
     } 

     public void AfterTextChanged(IEditable s) 
     { 

     } 

     public void BeforeTextChanged(ICharSequence amount, int start, int count, int after) 
     { 
      string value = amount.ToString(); 
      if (!value.Equals("")) 
      { 
       string cleanString = clearCurrencyToNumber(value); 
       string formattedAmount = transformtocurrency(cleanString); 
       lastAmount = formattedAmount; 
       lastCursorPosition = editText.SelectionStart; 
      } 
     } 

     public void OnTextChanged(ICharSequence amount, int start, int before, int count) 
     { 
      if (!amount.ToString().Equals(lastAmount)) 
      { 
       string cleanString = clearCurrencyToNumber(amount.ToString()); 
       try 
       { 
        string formattedAmount = transformtocurrency(cleanString); 
        editText.RemoveTextChangedListener(this); 
        editText.Text = formattedAmount; 
        editText.SetSelection(formattedAmount.Length); 
        editText.AddTextChangedListener(this); 

        if (lastCursorPosition != lastAmount.Length && lastCursorPosition != -1) 
        { 
         int lengthDelta = formattedAmount.Length - lastAmount.Length; 
         int newCursorOffset = Java.Lang.Math.Max(0, Java.Lang.Math.Min(formattedAmount.Length, lastCursorPosition + lengthDelta)); 
         editText.SetSelection(newCursorOffset); 
        } 
       } 
       catch (System.Exception e) 
       { 
        //log something 
       } 
      } 
     } 

     public static string clearCurrencyToNumber(string currencyValue) 
     { 
      string result = ""; 

      if (currencyValue == null) 
      { 
       result = ""; 
      } 
      else 
      { 
       result = Regex.Replace(currencyValue, "[^0-9]", ""); 
      } 
      return result; 
     } 

     public static string transformtocurrency(string value) 
     { 
      double parsed = double.Parse(value); 
      string formatted = NumberFormat.GetCurrencyInstance(new Locale("pt", "br")).Format((parsed/100)); 
      formatted = formatted.Replace("[^(0-9)(.,)]", ""); 
      return formatted; 
     } 

     public static bool isCurrencyValue(string currencyValue, bool podeSerZero) 
     { 
      bool result; 

      if (currencyValue == null || currencyValue.Length == 0) 
      { 
       result = false; 
      } 
      else 
      { 
       if (!podeSerZero && currencyValue.Equals("0,00")) 
       { 
        result = false; 
       } 
       else 
       { 
        result = true; 
       } 
      } 
      return result; 
     } 

     public void Dispose() 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

을 수행

using Android.App; 
using Android.OS; 
using Android.Widget; 

namespace TextWatcher 
{ 
    [Activity(Label = "Main2", MainLauncher = true)] 
    public class Main_Activity1 : Activity 
    { 
     private EditText editText; 

     protected override void OnCreate(Bundle savedInstanceState) 
     { 
      base.OnCreate(savedInstanceState); 
      SetContentView(Resource.Layout.Main); 

      editText = FindViewById<EditText>(Resource.Id.editText); 
      var watch = new CurrencyTextWatcher(editText); 

      editText.AddTextChangedListener(watch); 


     } 
    } 
} 

클래스, 오류가 아래의 이미지를 볼 수 발생

Help!

+0

예외가 발생한 행을 지정하십시오. –

+0

어떤 줄 번호가 실패합니까 ?? logcat에 파란색 밑줄이있는 오류 (텍스트는 빨간색 임)를 클릭하십시오 – Tasos

답변

0

귀하의 TextWatcher 구현이 작성 될 안드로이드 호출 가능 래퍼 (ACW)에 대한 위해 Java.Lang.Object 상속 할 필요가 있으므로이 개체 수있는 자바와 닷넷의 VM 사이에서 .

참조 : Android Callable Wrappers

독립형 감시자를 생성되기 때문에, Dispose하고 현재 구현에서 Handle

(필요한 경우, 당신은 Java.Lang.Object에있는 것들에 대한 재정을 필요합니다) 제거 예 :

public class CurrencyTextWatcher : Java.Lang.Object, ITextWatcher 
{ 

    public void AfterTextChanged(IEditable s) 
    { 
     //~~~~ 
    } 

    public void BeforeTextChanged(ICharSequence s, int start, int count, int after) 
    { 
     //~~~~ 
    } 

    public void OnTextChanged(ICharSequence s, int start, int before, int count) 
    { 
     //~~~~ 
    } 
} 

이제는 텍스트 감시자로 인스턴스를 생성하고 할당 할 수 있습니다.

+0

Tks Suchi! 그것은 효과가있다! –

관련 문제