2017-10-21 68 views
-1

它似乎運行良好,但我只是想知道爲什麼它顯示錯誤時,我嘗試實施類型轉換。爲什麼在示例中的類型轉換很重要?

例如,當ratingBar作爲(RatingBar)進行類型轉換時,以及editText作爲(EditText)進行類型轉換時。

有什麼建議嗎?指針?在你的XML聲明

package com.example.benmohammad.contacts; 


import android.app.Activity; 
import android.widget.EditText; 
import android.widget.RatingBar; 

class StudentFormViewHelper { 


private final Activity activity; 

public StudentFormViewHelper(Activity activity) { 

    this.activity = activity; 
} 

private String getName() { 

    return getTextFieldValue(R.id.student_form_name); 


} 
private String getTextFieldValue(int fieldId) { 

    EditText field = activity.findViewById(fieldId); 
    String value = field.getText().toString(); 
    return value; 
} 
private String getAddress() { 
    return getTextFieldValue(R.id.student_form_address); 
} 
private String getPhoneNumber() { 
    return getTextFieldValue(R.id.student_form_phonenumber); 

} 
private String getWebsite() { 
    return getTextFieldValue(R.id.student_form_website); 
} 
private String getEmail() { 
    return getTextFieldValue(R.id.student_form_email); 

} 

public Student createAStudent() { 
    return new Student(getName(), getAddress(), getPhoneNumber(), getWebsite(), getEmail(), getGrading()); 
} 

private double getGrading() { 
    RatingBar rating = activity.findViewById(R.id.student_form_grading); 
    return rating.getRating(); 
} 
} 
+0

你會得到什麼錯誤? – Srijith

+0

你在想什麼,在哪裏? – Juan

+0

它運行沒有類型轉換,這是我不明白 例如。 private double getGrading(){ RatingBar rating = activity.findViewById(R.id.student_form_grading); 看到,我還沒有在activity.findViewId之前類型強制轉換,但如果我這樣做...... 私人雙getGrading(){ 的RatingBar等級=(的RatingBar)activity.findViewById ......這夾頭下面的語法錯誤typecast「(RatingBar)」... 非常感謝 –

回答

0

類型轉換你的UI組件是重要的,因爲如果你訪問這些使用findViewById()返回一個View組件。因此,假設您正在使用EditText,如果您不將activity.findViewById("my_edit_text")的返回視圖投射到EditText,那麼您將使用View,並且可能會有某些您無法接聽或呼叫的操作或方法。看起來不太可能的是,您首先會將EditText設置爲View,並且看到一些錯誤。

相關問題