2013-07-05 34 views
0

我正在通過從另一個佈局中膨脹EditText視圖來創建EditText偵聽器。聽衆不起作用。我試圖在下面放置打印語句,但是在digitText.addTextChangedListener(...)之後都沒有打印。在它被調用之前的任何事情。我確信id是正確的,它沒有得到一個空指針來擴大視圖。有關爲什麼它不起作用的任何建議?EditText偵聽器未運行

public void digitsListener() { 

      LayoutInflater inflater = this.getLayoutInflater(); 
      View dialpadLayout = inflater.inflate(R.layout.dialpad, null); 
      EditText digitText = (EditText)dialpadLayout.findViewById(R.id.digits); 
      digitText.addTextChangedListener(new TextWatcher() { 

       @Override 
       public void onTextChanged(CharSequence s, int start, int before, int count) { 
        System.out.println("If this prints it works."); 
       } 

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

       @Override 
       public void afterTextChanged(Editable s) { 
       } 
      }); 
} 

這裏的dialpad.xml

<EditText 
     android:id="@+id/digits" 
     android:layout_width="0dip" 
     android:layout_height="match_parent" 
     android:background="@android:color/transparent" 
     android:focusable="true" 
     android:gravity="center" 
     android:layout_weight="0.6" 
     android:inputType="number" 
     android:scrollHorizontally="true" 
     android:textSize="40sp"/> 
+0

沒有是System.out.print()的機器人。使用日誌,而不是 – cgalvao1993

回答

0

EditText必須是在屏幕上可見,以便您可以與互動裏面的EditText視圖,所以也許你不需要inflaterinflater每次膨脹視圖時都會返回一個新對象。因此,您正在與之交互的EditText與inflater已返回的不同。如果你在一個活動中,你可以這樣改變你的代碼。

public void digitsListener() { 


      EditText digitText = (EditText) findViewById(R.id.digits); 
      digitText.addTextChangedListener(new TextWatcher() { 

       @Override 
       public void onTextChanged(CharSequence s, int start, int before, int count) { 
        System.out.println("If this prints it works."); 
       } 

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

       @Override 
       public void afterTextChanged(Editable s) { 
       } 
      }); 
} 
+0

卸下充氣崩潰()上'digitText.addTextChangedListener程序(新TextWatcher ..'用NPE – ono

+0

考慮一下吧。如果findViewById返回null意味着你的EditText是不可見的,我錯了? – Blackbelt

+0

這裏是我的情況:此活動正在調用4個其他片段作爲選項卡,我在主活動中運行此偵聽器,而不是其中一個片段。我應該將它放在適當的片段中嗎? – ono

0

你在Android上測試嗎?那麼有沒有System.out.print()

您需要使用的logcat來代替:

Log.i("tag", "If this prints it works");
只要選擇你想要的任何標記,它真的並不重要,你只需要通過使用標籤找到它:(例如標籤:錯誤)在上述logcat的搜索框

「Log.i」是信息,「Log.w」的警告,「Log.e」錯誤的消息

如果你想顯示

消息在您的手機上,您可以使用Toasts代替:

Toast toast = Toast.makeText(getApplicationContext(), "If this prints it works", Toast.LENGTH_SHORT);
toast.show();

(見here

+0

不,手機插入,我看在Eclipse的LogCat上的陳述 – ono

+0

不改變任何東西,沒有'System.out.print' –

+0

吐司也沒有出現 – ono