LoginSignup
4
2

More than 5 years have passed since last update.

Layoutをいじっただけor今まで動いてたのにClassCastExceptionが出て困っている方々へ

Last updated at Posted at 2018-02-28

何気ない、Androidではよく書くこんな記述。

    _checkbutton = (CheckBox) findViewById(R.id.checkbutton);
    _checkbutton.setChecked(true);

自分の場合は、CheckBoxだけじゃなくLinerLayoutのVisibleを変更させるだけのためにキャストなど
動いていたものが突然ClassCastExceptionを吐いて動かなくパターンなのですが
しかもonCreate()で・・

こういうパターンでClassCastExceptionを吐くなら

    LinearLayout mLinearLayout_main = (LinearLayout) findViewById(R.id.linearLayout_main);
    mLinearLayout_main.setVisibility(View.VISIBLE);

Castしなきゃいんだろ!と怒りながら

    findViewById(R.id.linearLayout_main).setVisibility(View.VISIBLE);

と書き換えますが、
CheckBoxのsetCheckedとかはCastしてからじゃないと扱えない・・

ちまちまLayoutをいじってると治ったり、
1dpなLinerLayoutを挿入して騙し騙し動かしてたのですが、
それでもまた動かなくなることが有って散々悩んでいた・・・
ふとおもって対応したのが以下のようなコード

    findViewById(R.id.checkbutton).post(new Runnable() {
        @Override
        public void run() {
            _checkbutton = (CheckBox) findViewById(R.id.checkbutton);
            _checkbutton.setChecked(true);
        }
    });

俗に言うUIスレッド云々かもですね
今のところこういう書き方にした所ClassCastExceptionは吐かなくなってます
悩んでる方お試しを・・

つーか、キャスト連発させるのって何なんでしょうね?

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2