android.support.constraint.ConstraintLayout无法强制转换为android.widget.Button错误

时间:2018-05-03 11:21:07

标签: java android android-widget

  

图片中的XML文件

xml file

more of xml file

以下是我的代码段:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //create a button for the letter at this position in the alphabet
        Button letterBtn;
        if (convertView == null) {
            //Inflate the button layout

我在下一行收到错误:

        letterBtn = (Button)letterInf.inflate(R.layout.letter, parent, false);
    } else {
        letterBtn = (Button) convertView;
    }
    //set the text to this letter
    letterBtn.setText(letters[position]);
    return letterBtn;
}

错误是:

android.support.constraint.ConstraintLayout cannot be cast to android.widget.Button

我不知道如何摆脱它

3 个答案:

答案 0 :(得分:0)

更改此行..

convertView =letterInf.inflate(R.layout.letter, parent, false);

答案 1 :(得分:0)

我认为您正在使用带有Constraint布局父级的按钮视图,该父级没有投射到按钮中,因此从行xml布局中查找按钮视图,然后您可以轻松地按下相关任务。

为了更好地澄清,请在此处粘贴xml

答案 2 :(得分:0)

您将始终遇到错误。如果你改变这一行

letterBtn = (Button)letterInf.inflate(R.layout.letter, parent, false);

convertView =letterInf.inflate(R.layout.letter, parent, false);

您仍然会在此(letterBtn = (Button) convertView)点发生错误。因为您无法将 ConstraintLayout 强制转换为按钮。 如果你想恢复你的按钮,只需给它一个像这个android:id="@+id/my_button_id"的id,然后用这样的方式在你的java代码中膨胀它:

convertView =letterInf.inflate(R.layout.letter, parent, false);
letterBtn = (Button)convertView.findViewById(R.id.my_button_id);
通过这种方式,您可以访问代码中的按钮。

亲切, 马修

编辑:顺便说一句,您的代码看起来像是适配器的内部。有什么意义呢。我只是因为你只返回按钮而感到有点困惑。

相关问题