0

您好,我已设法通过将 XML 文件扩展为片段将它们绑定到 ViewPagerIndicator,但我无法使用基本的 findViewById 代码将我的按钮引用到代码中。这是我的代码,因为有人可以帮忙

    package com.example.sliding;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class twoey extends Fragment {

    Button lol;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.two, null);
        return v;

        lol = (Button) findViewById (R.id.button1);

    }
}

但是,无论我尝试做什么,我都无法得到findViewById字的红色小线,有人可以帮忙吗?

4

3 回答 3

3

您的代码有 2 个错误:

  1. return v;必须是方法的最后一行,之后的任何一行都不能运行!无法访问,因此存在编译器错误!

  2. 这条线 lol = (Button) findViewById (R.id.button1);必须是lol = (Button) v.findViewById (R.id.button1);,否则您将拥有一条NullPointerException,因为button1它是活动的一部分,View v而不是活动。

正确的代码是:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.two, null);

    lol = (Button) v.findViewById (R.id.button1);
    return v;
}
于 2013-04-11T06:52:14.297 回答
0

覆盖onViewCreated(). 像这样:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
    lol = (Button) getView().findViewById (R.id.button1);

    .... // ANY OTHER CASTS YOU NEED TO USE IN THE FRAGMENT
}
于 2013-04-11T06:57:43.157 回答
0

Java 编译器根本无法访问return语句之后编写的代码。return意味着您已经完成了该方法并且您正在从中返回一个值,因此在此之后执行某些操作是没有意义的。因此,您需要在调用之前简单地移动lol = (Button) findViewById (R.id.button1)(实际上应该称为 as lol = (Button) v.findViewById (R.id.button1),因为v是您的根视图)return v,代码将正确编译。希望这可以帮助。

于 2013-04-11T06:55:19.190 回答