2012-11-29 3 views
0

MainActivity이 문제는 내가 classclastexception을한다는 것입니다

public class MainActivity extends Activity { 
// Declare our Views, so we can access them later 
private CheckUsernameEditText etUsername; 
private EditText etPassword; 
private EditText etPassword2; 
private Button btnRegister; 
private Button btnCancel; 
private TextView lblUserStatus; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // Set Activity Layout 
    setContentView(R.layout.activity_main); 

    // Get the EditText and Button References 
    etUsername = (CheckUsernameEditText) findViewById(R.id.username); 
    etPassword = (EditText) findViewById(R.id.password); 
    etPassword2 = (EditText) findViewById(R.id.password2); 
    btnRegister = (Button) findViewById(R.id.register_button); 
    btnCancel = (Button) findViewById(R.id.cancel_button); 
    lblUserStatus = (TextView) findViewById(R.id.userstatus); 

    // Set our new Listener to the Username EditText view 
    etUsername.setOnUsernameAvailableListener(new OnUsernameAvailableListener() { 
       @Override 
       public void onAvailableChecked(String username, 
         boolean available) { 
        // Handle the event here 
        if (!available) { 
         etUsername.setTextColor(Color.RED); 
         lblUserStatus 
           .setText(username 
             + " is already taken. Please choose another login name."); 
        } else { 
         etUsername.setTextColor(Color.GREEN); 
         lblUserStatus.setText(username + " is available."); 
        } 
       } 
      }); 

    // Set Click Listener 
    btnRegister.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // create Account 
     } 
    }); 
    btnCancel.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      // Close the application 
      finish(); 
     } 
    }); 
} 

대응하는 XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

      * 
      * 
<EditText 
    android:id="@+id/username" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:singleLine="true" /> 

      * 
      * 
</LinearLayout> 

CheckUsernameEditText

public class CheckUsernameEditText extends EditText implements OnKeyListener { 

OnUsernameAvailableListener onUsernameAvailableListener = null; 
final private static String[] registeredUsers = new String[] { 
     // This is just a fixed List for tutorial purposes 
     // in a real application you'd check this server sided or inside the 
     // database 
     "tseng", "admin", "root", "joedoe", "john" }; 

    public CheckUsernameEditText(Context context) { 
    super(context); 
    // Set KeyListener to ourself 
    this.setOnKeyListener(this); 
} 

public CheckUsernameEditText(Context context, AttributeSet attrs, 
     int defStyle) { 
    super(context, attrs, defStyle); 
    // Set KeyListener to ourself 
    this.setOnKeyListener(this); 
} 

public CheckUsernameEditText(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    // Set KeyListener to ourself 
    this.setOnKeyListener(this); 
} 

// Allows the user to set an Listener and react to the event 
public void setOnUsernameAvailableListener(
     OnUsernameAvailableListener listener) { 
    onUsernameAvailableListener = listener; 
} 

// This function is called after the check was complete 
private void OnUserChecked(String username, boolean available) { 
    // Check if the Listener was set, otherwise we'll get an Exception when 
    // we try to call it 
    if (onUsernameAvailableListener != null) { 
     // Only trigger the event, when we have a username 
     if (!TextUtils.isEmpty(username)) { 
      onUsernameAvailableListener.onAvailableChecked(username, 
        available); 
     } 
    } 
} 

@Override 
public boolean onKey(View v, int keycode, KeyEvent keyevent) { 
    // We only want to handle ACTION_UP events, when user releases a key 
    if (keyevent.getAction() == KeyEvent.ACTION_DOWN) 
     return false; 

    boolean available = true; 

    // Whenever a user press a key, check if the username is available 
    String username = getText().toString().toLowerCase(); 
    if (!TextUtils.isEmpty(username)) { 
     // Only perform check, if we have anything inside the EditText box 
     for (int i = 0; i < registeredUsers.length; i++) { 
      if (registeredUsers[i].equals(username)) { 
       available = false; 
       // Finish the loop, as the name is already taken 
       break; 
      } 
     } 
     // Trigger the Event and notify the user of our widget 
     OnUserChecked(username, available); 
     return false; 
    } 
    return false; 
} 

// Define our custom Listener interface 
public interface OnUsernameAvailableListener { 
    public abstract void onAvailableChecked(String username, 
      boolean available); 
} 
    } 

을 ClassCastExcptionAndroid. 내가 xml에 edittext라는 사용자 명을 선언하고 주 코드에서 CheckUsernameEditText로 선언하기 때문입니다. 이 문제를 어떻게 해결할 수 있습니까? 특히 CheckUsernameEditText가 EditText 클래스를 확장 할 때 캐스팅이 작동하지 않는 이유는 무엇입니까?

+0

'EditText'를'CheckUsernameEditText'로 캐스팅 할 수 없습니다! ** up ** ** ** ** **을 캐스팅 할 수 있습니다 (예 : ** 덜 구체적인 ** 클래스에만 캐스트 할 수 있지만 ** 더 구체적인 ** 클래스에는 캐스트 할 수 없음). 그것 :'CheckUsernameEditText'는'EditText'가 가지고 있지 않은 추가적인 메소드 및/또는 멤버 변수를 가지고 있습니다. –

답변

5

모든 CheckUsernameEditText 객체는 EditText 객체,
하지만이 모든 EditText 객체가 CheckUsernameEditText 객체입니다.

당신은 XML에 사용자 정의 클래스를 사용한다 : 나는 믿고

<your.package.name.CheckUsernameEditText 
    android:id="@+id/username" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:singleLine="true" /> 
+0

완벽한 설명 ;-) – noob

2

당신이 (당신의 사건 CheckUsernameEditText에서) 사용자 정의보기가 있다면 당신은 기억 ... XML에서 같은 선언해야 @Sam은 파생 클래스로 아래로 캐스트 할 수 없다는 것을 지적하므로 상급 클래스로 상위 캐스트 만 할 수 있으므로 CheckUsernameEditText보기를 항상 EditText (또는보기)로 캐스팅 할 수 있지만 다른 방법.