如何设置URI格式的imageswitcher?
我知道如何将其设置为URL而不是URI 我只是想知道如何将图像设置为实际应用程序中可用的资源?
这是我的代码:
private ImageSwitcher mAnswerImage;
// Set up Image Switcher
mAnswerImage = (ImageSwitcher) findViewById(R.id.ImageSwitcher_AnswerImage);
mAnswerImage.setFactory(new MyImageSwitcherFactory());
// Set the image of the imageswitcher
Drawable image = getQuestionImageDrawable(startingQuestionNumber);
mQuestionImage.setImageDrawable(image);
// Update question image
ImageSwitcher questionImageSwitcher = (ImageSwitcher) findViewById(R.id.ImageSwitcher_QuestionImage);
Drawable image = getQuestionImageDrawable(nextQuestionNumber);
questionImageSwitcher.setImageDrawable(image);
/**
* Returns a {@code String} representing the URL to an image for a particular question
*
* @param questionNumber
* The question to get the URL for
* @return A {@code String} for the URL or null if none found
*/
private String getQuestionImageUrl(Integer questionNumber) {
String url = null;
Question curQuestion = (Question) mQuestions.get(questionNumber);
if (curQuestion != null) {
url = curQuestion.mImageUrl;
}
return url;
}
/**
* Retrieves a {@code Drawable} object for a particular question
*
* @param questionNumber
* The question number to get the {@code Drawable} for
* @return A {@code Drawable} for the particular question, or a placeholder image if the loading failed or the question doesn't exist
*/
private Drawable getQuestionImageDrawable(int questionNumber) {
Drawable image;
URL imageUrl;
try {
// Create a Drawable by decoding a stream from a remote URL
imageUrl = new URL(getQuestionImageUrl(questionNumber));
InputStream stream = imageUrl.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
image = new BitmapDrawable(getResources(), bitmap);
} catch (Exception e) {
Log.e(DEBUG_TAG, "Decoding Bitmap stream failed");
image = getResources().getDrawable(R.drawable.noquestion);
}
return image;
}
/**
* A switcher factory for use with the question image. Creates the next
* {@code ImageView} object to animate to
*
*/
private class MyImageSwitcherFactory implements ViewSwitcher.ViewFactory {
public View makeView() {
ImageView imageView = (ImageView) LayoutInflater.from(
getApplicationContext()).inflate(
R.layout.image_switcher_view, mQuestionImage, false);
return imageView;
}
}
/**
* Object to manage the data for a single quiz question
*
*/
private class Question {
@SuppressWarnings("unused")
int mNumber;
String mText;
String mImageUrl;
/**
*
* Constructs a new question object
*
* @param questionNum
* The number of this question
* @param questionText
* The text for this question
* @param questionImageUrl
* A valid image Url to display with this question
*/
public Question(int questionNum, String questionText, String questionImageUrl) {
mNumber = questionNum;
mText = questionText;
mImageUrl = questionImageUrl;
}
}