【问题标题】:IllegalStateException upon clicking Toggle button inside ActionBar单击 ActionBar 内的 Toggle 按钮时出现 IllegalStateException
【发布时间】:2014-06-14 03:43:05
【问题描述】:

我有一个在操作栏中有一个切换按钮的应用程序。

我按照此处的说明操作,并显示了“切换”按钮: How to add a switch to android action bar?

我创建了一个新的布局(toggle_layout.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ToggleButton
    android:id="@+id/actionbartoggle
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="ON"
    android:textOff="OFF"
    android:onClick="onToggleClicked"/>
</RelativeLayout>

并使用上述说明中的项目修改了我的 menu.xml。

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/mytoggle"
        android:title=""
        android:showAsAction="always"
        android:actionLayout="@layout/toggle_layout" />   
</menu>

现在我正在尝试使用以下方法向它添加一个侦听器: http://developer.android.com/guide/topics/ui/controls/togglebutton.html

根据谷歌的示例代码,我需要在Activity中添加这个监听器:

public void onToggleClicked(View view) {
    // Is the toggle on?
    boolean on = ((ToggleButton) view).isChecked();
    if (on) {
        // Enable vibrate
    } else {
        // Disable vibrate
    }
}

我把它放在靠近我的活动顶部这一行之后:

public class MainActivity extends Activity implements ActionBar.TabListener {

应用程序运行,但是当我点击切换按钮时,我得到了这个:

06-13 12:17:22.663: E/AndroidRuntime(29436): java.lang.IllegalStateException: Could not find a  
method onToggleClicked(View) in the activity class android.view.ContextThemeWrapper for onClick 
handler on view class android.widget.ToggleButton with id 'actionbartoggle'

我做错了什么?

谢谢,非常感谢!

【问题讨论】:

    标签: android


    【解决方案1】:

    你不能像以前那样使用 onclick:

    通过执行以下操作在代码中附加点击处理程序: ToggleButton tb= findViewById(R.id. actionbartoggle);

    tb.setOnClickListener(new OnClickListener() {
    
       @Override
       public void onCLick(View v) {
        // do stuff
       }
    });
    

    java.lang.illegalstateexception could not find a method (view) in the activity class android fragment

    【讨论】:

    • 我是否将它放在我的 Activity 的 onCreate 中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2015-02-08
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多