片段中无法访问的代码错误

时间:2013-07-02 14:14:36

标签: android android-fragments oncreate findviewbyid

无法访问代码错误,不确定原因。任何帮助都会很棒,只有初学者。 获取第3行代码最终查看thumb1View = getView()。findViewById(R.id.thumb_button_1);

代码

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_zoom, container, false);


        final View thumb1View = getView().findViewById(R.id.thumb_button_1);
        thumb1View.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zoomImageFromThumb(thumb1View, R.drawable.image1);
            }
        });

        final View thumb2View = getView().findViewById(R.id.thumb_button_2);
        thumb2View.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zoomImageFromThumb(thumb2View, R.drawable.image2);
            }


        });

        // Retrieve and cache the system's default "short" animation time.
        mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);

        return thumb2View;

    }

2 个答案:

答案 0 :(得分:3)

由于您在第三行之前调用了一个返回,因此会出现指定的错误。

return inflater.inflate(R.layout.activity_zoom, container, false);

答案 1 :(得分:3)

编写此方法的正确方法如下:

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


    final View thumb1View = view.findViewById(R.id.thumb_button_1);
    thumb1View.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            zoomImageFromThumb(thumb1View, R.drawable.image1);
        }
    });

    final View thumb2View = view.findViewById(R.id.thumb_button_2);
    thumb2View.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            zoomImageFromThumb(thumb2View, R.drawable.image2);
        }


    });

    // Retrieve and cache the system's default "short" animation time.
    mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);

    return view;

}