【问题标题】:Cannot make a static reference to the non-static method findViewById(int) from the type Activity error [duplicate]无法从类型 Activity 错误中对非静态方法 findViewById(int) 进行静态引用 [重复]
【发布时间】:2014-07-20 17:05:12
【问题描述】:

您好,我在 Eclipse 上制作了一个计算器,我按照本教程完成了所有操作,但由于某种原因,我得到了“无法从 Activity 类型对非静态方法 findViewById(int) 进行静态引用” " 错误

public PlaceholderFragment() {

    int counter;
    Button add, sub;
    TextView display;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        counter = 0;
        add = (Button) findViewById(R.id.bAdd);
        sub = (Button) findViewById(R.id.bSub);
        display = (TextView) findViewById(R.id.tvDisplay);
        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter += 1;
                display.setText("Your total is " + counter);
            }
        });
        sub.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter -= 1;
                display.setText("Your total is " + counter);
            }
        });

        return rootView;
    }
}

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    Fragment 类没有findViewById() 方法;不过,Activity 确实如此。编译器抱怨因为这个 Fragment 是一个 Activity 的静态内部类,所以它认为你正在尝试调用该方法。

    如果您尝试从 Fragment 布局获取视图,请将 findViewById() 更改为 rootView.findViewById()

    如果您尝试从 Activity 布局中获取视图,请将其更改为 getActivity().findViewById()

    (这取决于bAdd 按钮的实际位置)。

    【讨论】:

    • 全部三个? @matiash
    • 是的。还有一件事:return rootView; 应该是方法的最后一行。
    • 编辑,现在我的计数器给我一个错误...“无法访问的代码”@matiash
    • 查看我之前关于退货声明的评论 :)
    • @user3692770 我编辑了您的代码以修复该部分(因为此错误实际上与问题无关)。看看return rootView 现在在哪里。
    猜你喜欢
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多