Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

android - How to load picture from @drawable to ImageView using fragments?

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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to do is:

TypedArray typedArray = res.obtainTypedArray(R.array.images);

...

image.setImageDrawable(typedArray.getDrawable(position, -1));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...