我的代码在线上无法访问的语句有错误,该语句已定义图像切换器
public class mainFragment extends Fragment implements ViewSwitcher.ViewFactory{
private OnFragmentInteractionListener mListener;
public mainFragment() {
// Required empty public constructor
}
int cnt= 0;
int imgs[]={
R.drawable.mah_121,
R.drawable.tamashagar_207,
R.drawable.tandorosti_149
};
ImageSwitcher imgSwitcher;
//final ImageView imageView;
//ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
imgSwitcher = (ImageSwitcher) getView().findViewById(R.id.imageSwitcher);
imgSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(getActivity());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
//imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
return imageView;
}
});
imgSwitcher.setImageResource(imgs[cnt]);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public View makeView() {
return null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
在
行imgSwitcher = (ImageSwitcher) getView().findViewById(R.id.imageSwitcher);
我在imageview定义中使用getActivity后出现“错误无法访问语句”我有这个问题
答案 0 :(得分:1)
那是因为你在开始时从那个方法返回:
return inflater.inflate(R.layout.fragment_main, container, false);
尝试:
View view = inflater.inflate(R.layout.fragment_main, container, false);
imgSwitcher = (ImageSwitcher) view.findViewById(R.id.imageSwitcher);
然后作为该函数的最后一行:
return view;
答案 1 :(得分:0)
return ...;
之后你没有任何东西(评论和空白除外)!
值得将与imgSwitcher
相关的代码移至onViewCreated
。