2014-08-28 138 views
0

我正在創建自定義首選項<com.myproject.CustomPreference android:layout="@layout/preferences_main" />,我想在其中顯示用戶名,電話號碼和個人資料圖片(在一個不重要的圓圈內)。我設法從CustomPreference.class擴展偏好設置中獲得用戶名和電話號碼,但我沒有得到配置文件圖片的路徑,因爲getExternalFilesDir對於此類沒有定義。 這裏是我的代碼:getExternalFilesDir在自定義首選項中未定義

public class CustomPreference extends Preference { 
    private TextView tvusername, tvphonenumber; 
    private ImageView profilepic_profile; 

public CustomPreference(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    this.setWidgetLayoutResource(R.layout.preferences_main); 
} 

@Override 
protected void onBindView(View view) { 
    super.onBindView(view); 
    tvusername = (TextView) view.findViewById(R.id.tvusername); 
    tvphonenumber = (TextView) view.findViewById(R.id.tvphonenumber); 
    profilepic_profile = (ImageView) view 
      .findViewById(R.id.profilepic_profile); 

    final SharedPreferences prefs = getSharedPreferences(); 

    // entering preference username in text view 
    String username = prefs.getString("username", null); 
    tvusername.setText(username); 

    // entering preference phonenumber in text view 
    String phonenumber = prefs.getString("phonenumber", null); 
    tvphonenumber.setText(phonenumber); 

    // Show currently saved profile pic in imageview 

    String fname = "profile.png"; 
    Bitmap photo2 = BitmapFactory.decodeFile(getExternalFilesDir(null) 
      .getAbsolutePath() + "/images/" + fname); 
    if (photo2 != null) { 
     GraphicsUtil graphicUtil2 = new GraphicsUtil(); 
     profilepic_profile.setImageBitmap(graphicUtil2.getCircleBitmap(
       photo2, 16)); 
    } else { 
     // profilepic_profile.setBackground(profile_pic_big); 
    } 
} 

} 

回答

1

getExternalFilesDirContext類的一種方法。

所以在你mContext類,並在構造函數創建一個全局Context

public CustomPreference(Context context, AttributeSet attrs) 
{ 
    super(context, attrs); 
    mContext = context 
    this.setWidgetLayoutResource(R.layout.preferences_main); 
} 

,然後你可以使用mContext調用getExternalFilesDir

mContext.getExternalFilesDir() 

OR

您可以撥打

getContext().getExternalFilesDir() 
+0

這麼簡單,我花了一些時間沒有任何成功 - 非常感謝。 – sascha 2014-08-28 14:22:43

+0

@Apoorv可能的編輯。不要保存上下文,當os進行清理時,它可能會導致問題,因爲可能有東西與它鏈接。而是保存getExternalFilesDir()的結果 – danny117 2014-08-28 19:05:56

2

getExternalFilesDir()Context的方法。您在CustomPreference中通過了Context,並且它繼承了Preference基類中的getContext()方法。