繁体   English   中英

如何将小部件切换的状态从选中更改为取消选中?

[英]How I can change state of widget switch from check to uncheck?

我想从thingspeak接收数据并自动将开关的状态从选中状态更改为未选中状态,反之亦然。
这是我的代码,但是不起作用,只能设置文本但不能更改状态。
请帮我!

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

        button = (Button) findViewById(R.id.button);

        myswitch1 = (Switch) findViewById(R.id.switch1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        postdata2();
                    }
                });
                t.start();
                now_da1.setText(get_da1);
                if(get_dk1 == "1") {
                      myswitch1.setChecked(False);
                }   
                else if (get_dk1 =="0") {
                      myswitch1.setChecked(True);
                }
            }
        });

        myswitch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        t1 = "1";
                    } else {
                        t1 = "0";
                    }
                }
            });

        public void postdata2() {
        HttpRequest mReq = new HttpRequest();
        get_t1 =    mReq.sendGet("https://thingspeak.com/channels/106453/field/1/last");

        get_da1 = get_t1.substring(0, 2);
        get_dk1 = get_t1.substring(3, 3);
        Log.d(myGet, get_dk1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

使用此myswitch1.setChecked(false); 取消选中myswitch1.setChecked(true); 进行检查。

快乐编码:)

比较两个Strings的值时,请始终使用equals()方法比较值,而不要使用==比较对象引用

例如:

String first = "1";
String second = "1";

first == second将返回false,因为它们未引用同一对象。 但是, first.equals(second)将返回true,因为两个Strings的值相同。

您可以尝试使用以下条件替换条件:

if (get_dk1.equals("1")) {
    myswitch1.setChecked(false);
} else if (get_dk1.equals("0")) {
    myswitch1.setChecked(true);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM