问题
How to load picture from @drawable to ImageView using fragments? In every single fragment I have other picture. With array of String that's works, but with pictures doesn't. It's only returns 0.
XML Array (PS. also doesn't work)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="images">
<item>@drawable/one</item>
<item>@drawable/two</item>
</array>
</resources >
XML View:
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="15" />
JAVA:
public class ShowElements extends Fragment {
final static String ARG_POSITION = "position";
int mCurrentPosition = -1;
String[] authorsNicks;
int[] imageMain;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
authorsNicks = res.getStringArray(R.array.authors_nicks);
imageMain = res.getIntArray(R.array.images);
return...
}
public void updateArticleView(int position) {
TextView autorTextView = (TextView) getActivity().findViewById(
R.id.author);
autorTextView.setText(authorsNicks[position]);
//image.setImageResource(R.drawable.one); It load picture
image.setImageResource(imageMain[position]); //No picture in view
Log.i("qwerty",String.valueOf(imageMain[position])); // 0 in LogCat
mCurrentPosition = position;
}
回答1:
You have to do the next:
public class ShowElements extends Fragment {
final static String ARG_POSITION = "position"; int mCurrentPosition = -1; String[] authorsNicks; TypeArray imageMain;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
... authorsNicks = res.getStringArray(R.array.authors_nicks); imageMain = res.obtainTypedArray(R.array.images); return... }
public void updateArticleView(int position) { TextView autorTextView = (TextView) getActivity().findViewById( R.id.author); autorTextView.setText(authorsNicks[position]);
//image.setImageResource(R.drawable.one); It load picture image.setImageResource(imageMain.getResourceId(position, -1)); //It should load your picture Log.i("qwerty",String.valueOf(imageMain[position])); // 0 in LogCat mCurrentPosition = position; }
回答2:
What you want to do is:
TypedArray typedArray = res.obtainTypedArray(R.array.images);
...
image.setImageDrawable(typedArray.getDrawable(position, -1));
回答3:
May be defining drawable ids in resources as array is your requirement. but why to struggle that much to save id array in resources and get them using Resources
and TypedArray
and setting programmatically?
you can define your drawable id array programmatically and use it.
public class ShowElements extends Fragment {
.......
private static final int[] imageMain = new int[]{R.drawable.one,R.drawble.two};
......
public View onCreateView(......) {
........
}
}
回答4:
use
getResources().getDrawable(R.id.myImage);
来源:https://stackoverflow.com/questions/20398329/how-to-load-picture-from-drawable-to-imageview-using-fragments