Я довольно новый в Android, и я нахожу некоторые результаты, чтобы сделать следующее, связанное с контекстом.Как получить объект Context в фрагмент, расширяющий класс?
Так у меня есть класс, который содержит метод полезности, создавать и возвращать Bitmap изображения, это код моего класса:
public class ImgUtility {
/**
* Method that create the images related to the difficulty of a recepy
* @param context
* @param difficulty that represent the number of chef_hat_ok into the final image
* @return a Bitmap representing the difficult of a recepy
*/
public static Bitmap createRankingImg(Context context, int difficulty) {
// Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chef_hat_ok);
// Create a new image bitmap having width to hold 5 star.png image:
Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth() * 5, myBitmap.getHeight(), Bitmap.Config.RGB_565);
/* Attach a brand new canvas to this new Bitmap.
The Canvas class holds the "draw" calls. To draw something, you need 4 basic components:
1) a Bitmap to hold the pixels.
2) a Canvas to host the draw calls (writing into the bitmap).
3) a drawing primitive (e.g. Rect, Path, text, Bitmap).
4) a paint (to describe the colors and styles for the drawing).
*/
Canvas tempCanvas = new Canvas(tempBitmap);
// Draw the image bitmap into the cavas:
tempCanvas.drawBitmap(myBitmap, 0, 0, null);
tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth(), 0, null);
tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 2, 0, null);
tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 3, 0, null);
tempCanvas.drawBitmap(myBitmap, myBitmap.getWidth() * 4, 0, null);
return tempBitmap;
}
}
Как вы можете видеть, этот класс содержит createRankingImg(), которые принимают параметр Контекст как параметр и используют его для создания изображения. Этот объект используется для извлечения изображения из ресурсов (в метод BitmapFactory.decodeResource()). Что именно представляет объект Context в приложении Android?
Я знаю, что для получения контекста в класс деятельности я могу использовать GetResources() метода.
Моя проблема заключается в том, что я должен получить контекст в класс, который exentends Fragment.
У меня есть что-то вроде этого:
public class ScreenSlidePageFragment extends Fragment {
.......................................................................
.......................................................................
.......................................................................
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
.....................................................................
.....................................................................
.....................................................................
switch (mPageNumber + 1) {
case 1:
imgSlideView.setImageResource(R.drawable.carbonara);
((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.carbonara));
ImageView difficultyContainerImageView1 = (ImageView) rootView.findViewById(R.id.difficultyContainer);
difficultyContainerImageView1.setImageDrawable(new BitmapDrawable(getResources(), ImgUtility.createRankingImg(getApplicationContext(), 3)));
break;
.....................................................................
.....................................................................
.....................................................................
}
return rootView;
}
Моя проблема заключается в том, что, когда в предыдущем классе фрагмента я вызываю метод:
ImgUtility.createRankingImg(getResources(), 3)
передавая ему GetResources() выход (что я подумал дать мне Контекст, IDE сообщит мне следующее сообщение об ошибке:
Неверный тип 1-го аргумента. Найдено: «android.content.res.Resources», требуется: «android.content.Context»
Так что, мне кажется, что в класс, который расширяет фрагмент и не активностьgetResources() метод return a Ресурсы объект вместо a Контекст объект (как сделано в класс Activity). Это правда? Зачем?
Как получить контекст внутри класса, который расширяет фрагмент? И что именно представляет контекст в приложении для Android? Что мне не хватает? Как я могу решить эту проблему?
'getActivity()' –
Он говорит мне: «Не удается восстановить getActivity()»? Зачем? – AndreaNobili
'getActivity()' определяется в разделе «Фрагмент», поэтому, видимо, вы не в «Фрагменте», либо есть опечатка или что-то в этом роде. – laalto