我認爲來自Google的官方code style guidelines非常有幫助,但它們不包括視圖元素的命名約定。Android小部件命名約定
比方說,我們簡單的Activity包含一個ImageView,一個TextView和Button。代碼看起來像這樣:
class SimpleActivity extends Activity {
private ImageView mImageView;
private TextView mTextView;
private Button mButton;
}
當然,我們不會給這些名稱的小部件,因爲他們不描述。我們應該知道這個小部件的功能。因此,讓我們設想ImageView表示用戶配置文件圖像,TextView表示用戶名,Button表示繼續按鈕。
我會分裂可能的命名約定三類:
class SimpleActivity extends Activity {
private ImageView mUserProfileImageView;
private TextView mUsernameTextView;
private Button mContinueButton;
}
第一慣例的一大優勢是,雖然使用的代碼成員,我們知道這是TextView的我們例如可以使用「setText()」方法。不幸的名字很長,因爲懶惰的程序員是好程序員,這是它的缺點。
2.
class SimpleActivity extends Activity {
private ImageView mUserProfileImage;
private TextView mUsernameText;
private Button mContinueButton;
}
在這裏,我們有混合慣例,我們仍然知道什麼樣的部件它,而在代碼中使用的地方是,但也許當我們有小部件的更復雜的功能,這些名字將是還太長?
class SimpleActivity extends Activity {
private ImageView mUserProfile;
private TextView mUsername;
private Button mContinue;
}
最懶的類別。
問題
你在代碼中使用哪種命名約定,什麼是你的經驗?也許有更好的約定,我沒有提到? Google正在使用什麼樣的會議?
我使用「命名約定」,這是我從VB和VB.NET時代遷移而來的。我爲TextViews使用了前綴'txt',ImageViews使用了'img',按鈕使用了'btn',並且我使用了'FRG_','ACT_','CLS_'作爲Activities,Fragments和Classes名稱(因爲它們必須以大寫字母開頭)。通常,我不使用前綴變量。但我可以使用'bln','str','int',...如果我想。 –