LinearLayout cannot be cast to android.widget.checkbox

丶灬走出姿态 提交于 2019-12-13 06:13:01

问题


The problem that I am facing is that my app crashes at launch with the above error when the following statement is included.

  external= (CheckBox) menu.findItem(R.id.location).getActionView();

The code block with this statement is

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // TODO Auto-generated method stub
    new MenuInflater(this).inflate(R.menu.actions,menu);
    Log.d("Action","inflated");
    external= (CheckBox) menu.findItem(R.id.location).getActionView();   <<<error
    Log.d("Action","external initialized");
    return super.onCreateOptionsMenu(menu);
}

external is a data member of the same class declared as

private CheckBox external=null;

The menu that is inflated is :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item 
     android:id="@+id/location"
     android:actionLayout="@layout/action_location"
     android:showAsAction="never">

</item>
<item 
    android:id="@+id/save" 
    android:title="Save" 
    android:showAsAction="always">

</item>
<item 
    android:id="@+id/saveBackground" 
    android:showAsAction="always|withText"
    android:title="in BG">

</item>

If that particular line is commented out, the app launches just fine. What could be the issue ?

[UPDATE] Here's the action_location.xml content

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox 
    android:id="@+id/external"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:title="@string/external"
    />


</LinearLayout>

回答1:


getActionView() returns the currently set action view for this menu item. Try this way

View view =  menu.findItem(R.id.location).getActionView(); 
CheckBox checkBox = view.findViewById(R.id.external);



回答2:


try this:

external= (CheckBox) menu.findItem(R.id.location).getActionView().getChildAt(0);

This line:

external= (CheckBox) menu.findItem(R.id.location).getActionView();

actually gets the parent linear layout.




回答3:


getActionView gets you the layout, not the checkbox.

try

external= (CheckBox) menu.findItem(R.id.location)
             .getActionView()
             .findViewById(R.id.external);


来源:https://stackoverflow.com/questions/17814727/linearlayout-cannot-be-cast-to-android-widget-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!