2014-08-28 34 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()方法。