如何使用片段将图片从@drawable加载到ImageView? 在每个片段中我都有其他图片。随着String的数组工作,但图片没有。它只返回0.
XML数组(PS。也不起作用)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="images">
<item>@drawable/one</item>
<item>@drawable/two</item>
</array>
</resources >
XML视图:
<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;
}
答案 0 :(得分:2)
您想要做的是:
TypedArray typedArray = res.obtainTypedArray(R.array.images);
...
image.setImageDrawable(typedArray.getDrawable(position, -1));
答案 1 :(得分:1)
你必须做下一个:
public class ShowElements扩展Fragment {
final static String ARG_POSITION = "position"; int mCurrentPosition = -1; String[] authorsNicks; TypeArray imageMain;
public View onCreateView(LayoutInflater inflater,ViewGroup容器, 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 [位置]);
//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 :(得分:0)
可能在资源中定义可绘制的ID,因为数组是您的要求。但为什么要努力保存资源中的id数组并使用Resources
和TypedArray
并以编程方式设置?
您可以通过编程方式定义可绘制的id数组并使用它。
public class ShowElements extends Fragment {
.......
private static final int[] imageMain = new int[]{R.drawable.one,R.drawble.two};
......
public View onCreateView(......) {
........
}
}
答案 3 :(得分:-2)
使用
。getResources()getDrawable(R.id.myImage);