【问题标题】:The method findViewById(int) is undefined for the type该类型的方法 findViewById(int) 未定义
【发布时间】:2013-01-21 22:35:16
【问题描述】:

我得到了错误

类型 PM_section 的 findViewById(int) 方法未定义

在尝试实现我的可扩展列表视图时。我确信这是一个常见错误,但我无法找到解决方案。我正在尝试学习碎片等,从我开始就一直是一场艰苦的战斗。我进行了相当多的搜索,发现了很多结果,这似乎对我的情况没有帮助。

如果有人能给我任何见解,或指出正确的方向,我将不胜感激。

下面是我的小测试课

public class PM_section extends Fragment {
//  CustomExpListView custExpListView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        View V = inflater.inflate(R.layout.fragment_pm_section_test, container, false);

        CustomExpListView custExpListView = (CustomExpListView)
                this.findViewById(R.id.ExpandableListView01);
        return V;   
    }// end on create
}

CustomExpListView 类几乎是从 Android 示例项目中复制而来的,并且很高兴并且没有问题。

谢谢你帮助我。

【问题讨论】:

    标签: android fragment expandablelistview


    【解决方案1】:

    如果R.id.ExpandableListView01R.layout.fragment_pm_section_test 的一部分,则将this 替换为V

    CustomExpListView custExpListView = (CustomExpListView)
                    V.findViewById(R.id.ExpandableListView01);
    

    Fragments 没有findViewById() 方法。您需要使用膨胀的View 来从您的布局中获取所有内容。

    还可以考虑使用 Java 命名约定。变量以小写字母开头,而类以大写字母开头。

    【讨论】:

    • 即使我用 V 替换它,我也会收到错误 Cannot cast from View to CustomExpListView
    • 你复制的完全一样吗?你仍然需要后面的括号,所以它看起来像=(CustomExpListView)。如果您仍然遇到该错误,您应该清理您的项目,演员应该是正确的。
    • 另外,如果清理不起作用,您是否绝对确定CustomExpListView 扩展ListViewView
    • 是的,我将它复制并粘贴到现有代码上。我还清理了项目。错误并没有消失。
    • 那么我唯一的错误就是CustomExpListView 没有扩展视图类型。介意在此处发布课程(如您的代码所示)吗?
    【解决方案2】:

    只需调用getView()获取fragment的根视图,然后调用findViewById()方法即可:

    getView().findViewById(R.id.ExpandableListView01);
    

    没有它,您将无法使用findViewById(),因为Fragment 类本身没有这样的方法。

    【讨论】:

    • 嗯,你能用getView()获得视图之前片段的onCreateView()返回了吗?即使可以,这也是一个多余的方法调用,您已经在方法中提供了根视图 (V)。
    • 我在实现 CustomExpListView 时收到此错误 custExpListView = (CustomExpListView) getView().findViewById(R.id.ExpandableListView01); - 无法从 View 投射到 CustomExpListView
    • @A--C 你说得对,我没注意也没注意到它在 onCreateView() 方法里面,抱歉。当然,在这种情况下 A--C 的答案会更好。我的更一般。
    • 我很抱歉我的无知,但是这将如何设置?我是否将 custExpListView 放在 onCreate 中?这会在片段的 onCreateView() 之前获得视图吗?
    • @user1927326 只需将this 替换为V 就像我的回答一样,您应该会很好。话虽如此,不,onCreate()onCreateView() 之前被调用。请参阅Fragment lifecycle。从onStart()onStop() 以及介于两者之间的所有其他内容,您都可以使用getView(),因为根布局视图现已创建
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多