我想在片段活动中的imageview中实现随机图像。我受到了堆栈社区问题的启发,但没有一个片段。
以下是代码:
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);
无法访问的声明
问题出在哪里?
答案 0 :(得分: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
}