2014-06-22 3 views
0

내 응용 프로그램에서 EditText와 함께 AlertDialog를 사용하고 있습니다. 몇 번 호출했기 때문에이 코드를 메서드로 옮기고 싶습니다.메서드에서 EditText가있는 AlertDialog : 로컬 변수 editText가 초기화되지 않았을 수 있습니다.

private EditText showEditAlert(DialogInterface.OnClickListener listener) { 
    AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    alert.setTitle(R.string.waypoint); 
    alert.setMessage(R.string.waypoint_alert_text); 
    EditText editText = new EditText(this); 
    alert.setView(editText); 
    alert.setPositiveButton(android.R.string.ok, listener); 
    alert.setNegativeButton(android.R.string.cancel, null); 
    alert.show(); 
    return editText; 
} 

을 그리고 나는 그것을 사용하려면 : :이 방법으로 그것을 구현하려고

final EditText editText = showEditAlert(new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
     // Here is I am working with editText 
     // and here is I get error "The local variable editText may not have been initialized" 
    } 
}); 

하지만 "지역 변수 EDITTEXT가 초기화되지 않았을 수 있습니다"오류가 발생합니다. 컴파일러는 showEditAlert()가 value를 반환하기 전에 onClick() 메서드가 호출 될 것이라고 생각합니다.

올바르게 구현하는 방법은 무엇입니까? 아니면 그냥이 오류를 억제 할 수 있습니까?

+0

가 오류가 나 편집자에 의해 주어진 경고? – amd

+0

@ amd, 즉 편집기 (Eclipse)에서 제공 한 오류입니다. – BArtWell

답변

1

IDE의 경고가 사용자가 가정 한 이유와 정확하게 일치하는 것처럼 보입니다. 난 당신이 청취자에 대한 사용자 정의 인터페이스를 정의하여 이것을 피할 수있을 것 같아요 (부팅하는 데 사용하는 것이 더 분명합니다). 같은 뭔가 :

showEditAlert(new EditAlertOkListener() { 
     @Override 
     public void onEditAlertOk(EditText editText) { 
      // Use editText here. 
     } 
    });  

PS : 다음

interface EditAlertOkListener 
{ 
    void onEditAlertOk(EditText editText); 
} 

private void showEditAlert(final EditAlertOkListener listener) 
{ 
    AlertDialog.Builder alert = new AlertDialog.Builder(this); 
    ... 
    final EditText editText = new EditText(this); 
    alert.setView(editText); 
    alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() 
    { 
     @Override 
     public void onClick(DialogInterface dialog, int which) 
     { 
      if (listener != null) 
       listener.onEditAlertOk(editText); 
     } 
    }); 

    alert.setNegativeButton(android.R.string.cancel, null); 
    alert.show(); 
} 

그리고는 그것을 호출합니다. 또한이 메소드가 EditText을 반환하게 할 수도 있습니다. 필요한 경우이 예제를 더 명확하게 만들기 위해 방금 제거했습니다. 또는 EditText 콘텐츠가 필요하면 EditText 대신 CharSequence 또는 String을 전달해야합니다. 이것은 단지 템플릿 일뿐입니다. :)

+0

답변 해 주셔서 감사합니다! 당신이 그것을 위해 커스텀 리스너를 만들 것을 제안하는 것을 보았습니다. 이것에 대해서도 생각 합니다만, 내장 된 청취자만으로도이 작업을 수행 할 수 있기를 바랍니다. 그러나 그것이 최선의 방법 인 것처럼 보입니다. – BArtWell

0

editText 변수가 초기화되지 않을 수 있습니다. IDE가 생성 중일 때이를 확인하지 못했습니다.

여기에이 솔루션은 키워드를 사용하는 것입니다 : "이"

final EditText editText = showEditAlert(new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
     this.getText();// this mean editText, not its parent, if you want to use parent, you must have ParentClass.this 
    } 
}); 
관련 문제