2016-12-13 2 views
0

Я хотел реализовать случайное изображение в изображении в моей активности фрагмента. Меня вдохновляет вопрос сообщества о стеке, но для фрагмента не было.Случайное изображение в ImageView in Fragment

Вот код:

public class OneFragment extends Fragment { 
     final Random rnd = new Random(); 
     ImageView img; 

    public OneFragment() { 
     // Required empty public constructor 
    } 

    private static TextView creditWallet; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    public static void onUpdateView(Context aiContext) { 
     // TODO Auto-generated method stub 
     if (aiContext != null && creditWallet != null) 
      creditWallet.setText(PreferenceConnector.readInteger(aiContext, PreferenceConnector.WALLETPOINTS, 0) + ""); 

    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_one, container, false); 

     super.onViewCreated(view, savedInstanceState); 

     // Inflate the layout for this fragment 

     final ImageView img = (ImageView) view.findViewById(R.id.imgRandom); 
     return view; 


     // I have 3 images named img_0 to img_2, so... 
     final String str = "img_" + rnd.nextInt(2); 
     img.setImageDrawable 
       (
         getResources().getDrawable(getResourceID(str, "drawable", 
           getApplicationContext())) 
       );} 


    protected final static int getResourceID 
      (final String resName, final String resType, final Context ctx) { 

     final int ResourceID =ctx.getResources(). 
            getIdentifier(resName, resType, 
            ctx.getApplicationInfo().packageName); 
     if (ResourceID == 0) { 
      throw new IllegalArgumentException 
        (
          "No resource string found with name " + resName 
        ); 
     } else { 
      return ResourceID; 
     } 

    } 

} 

Но у меня есть ошибка в этой строке:

final String str = "img_" + rnd.nextInt(2); 

недостижим заявление

Где проблема?

ответ

2

После этого return view; ничего будет выполняться так, что вам нужно, чтобы переместить return заявление в конце вашей onCreateView функции

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_one, container, false); 

    super.onViewCreated(view, savedInstanceState); 

    // Inflate the layout for this fragment 

    final ImageView img = (ImageView) view.findViewById(R.id.imgRandom); 
// return view; 
// ^^^^ error remove it 

    // I have 3 images named img_0 to img_2, so... 
    final String str = "img_" + rnd.nextInt(2); 
    img.setImageDrawable 
      (
        getResources().getDrawable(getResourceID(str, "drawable", 
          getApplicationContext())) 
      ); 
    return view; 
    // ^^^ move it here 
}