4
package com.example.koustav.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    Switch swi = (Switch) findViewById(R.id.swch);
    swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) //Line A
        {

        }
    });

    public void onClick(View view)
    {
        boolean isOn = ((Switch) view).isChecked();

        if (isOn)
        {
            ((TextView) findViewById(R.id.largey)).setTextColor(getResources().getColor(R.color.black));
        }
        else
        {
            ((TextView) findViewById(R.id.largey)).setTextColor(getResources().getColor(R.color.white));
        }

    }

}

我正在为这个项目使用 Android Studio。我已经在互联网上搜索了可扩展的解决方案,但找不到。

我一直在尝试使用setOnCheckedChangeListener一个Switch对象。但是,无论我尝试什么,我总是会收到无法解析符号“setOnCheckedChangeListener”错误。此外,在 A 行,对象 buttonView 带有红色下划线,给出相同的错误Cannot Resolve Symbol 'buttonView'

我已经导入了必要的(并推荐给其他人作为答案)类。我正在使用适用于 android 4.0 及更高版本的 API。我基本上希望onClick通过侦听器重新实现该方法,因为侦听器可以同时使用点击和滑动,而onClick仅适用于点击而不是滑动。

4

3 回答 3

8

你必须在Switch里面初始化onCreate()

于 2015-04-24T10:31:55.237 回答
5

移动

  Switch swi = (Switch) findViewById(R.id.swch);
  swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) //Line A
        {

        }
    });

onCreate. 在创建活动之前,您不能调用findViewById, 并且swi.setOnCheckedChangeListener(..);不是有效语句

于 2015-04-24T10:33:37.770 回答
0

替换下面的代码

        switchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SwitchButton switchButton = (SwitchButton)view;

经过

        switchButton.setOnCheckedChangeListener( new SwitchButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SwitchButton switchButton = (SwitchButton) buttonView;

它会工作的!

于 2017-02-14T07:36:10.967 回答