2014-08-28 3 views
0

Я создаю пользовательский префикс <com.myproject.CustomPreference android:layout="@layout/preferences_main" />, где я хочу показать имя пользователя, номер телефона и профиль pic (в круге, который еще не имеет значения). Мне удалось получить имя пользователя и номер телефона из настроек с помощью расширения CustomPreference.class, но я не получаю путь к профилю pic, потому что 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

getExternalFilesDir - метод Context класс.

Так создать глобальную Context в своем классе mContext и в конструкторе сделать

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

, а затем вы можете использовать mContext позвонить getExternalFilesDir

mContext.getExternalFilesDir() 

ИЛИ

вы можете позвонить

getContext().getExternalFilesDir() 
+0

Так просто, и я провел некоторое время без всякого успеха - большое спасибо. – sascha

+0

@Apoorv возможно редактирование. Не сохраняйте контекст, который, вероятно, вызовет проблему, когда os сделает очистку, потому что, возможно, что-то связано с ней. Вместо этого сохраните результат из getExternalFilesDir() – danny117

2

getExternalFilesDir() является метод на Context. Вам передается Context в CustomPreference, и он наследует метод getContext() от базового класса Preference.

Смежные вопросы