Android CheckedTextView how to update the view

249 Views Asked by At

I have programmatically added CheckedTextView to the linearlayout view. Please look at following code:

private LinearLayout linearLayout;
private CheckedTextView checkedtextview;
    linearLayout = (LinearLayout) findViewById(R.id.statusView);
    checkedtextview = new CheckedTextView(ScanStatus.this, null, android.R.attr.listChoiceIndicatorMultiple);
    checkedtextview.setText(R.string.applications);
    linearLayout.addView(checkedtextview);

Later in code I have to update the checkedtextview like below:

checkedtextview.setCheckMarkDrawable(getDrawable(R.mipmap.check1));
checkedtextview.setChecked(true);
checkedtextview.setTextColor(Color.GREEN);
linearLayout.addView(checkedtextview);

But this results in crash with following log:

D/AndroidRuntime(24818): Shutting down VM E/AndroidRuntime(24818): FATAL EXCEPTION: main E/AndroidRuntime(24818): Process: com.example.ashwini.timapp, PID: 24818 E/AndroidRuntime(24818): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

Please suggest me how can I update the view?

4

There are 4 best solutions below

3
A. Shevchuk On BEST ANSWER

You have two options. First, if you have a reference to your checkedtextview all the time - you can update it without calling addView:

    checkedtextview.setCheckMarkDrawable(getDrawable(R.mipmap.check1));
checkedtextview.setChecked(true);
checkedtextview.setTextColor(Color.GREEN);.   

In the second case use tip from @坚持远方 answer:

    linearLayout.removeView(checkedtextview);
checkedtextview.setCheckMarkDrawable(getDrawable(R.mipmap.check1));
checkedtextview.setChecked(true); 
checkedtextview.setTextColor(Color.GREEN); 
linearLayout.addView(checkedtextview);
0
坚持远方 On

i think first you need removed the view,then update it.

linearLayout.removeView(checkedtextview);
checkedtextview.setCheckMarkDrawable(getDrawable(R.mipmap.check1));
checkedtextview.setChecked(true); 
checkedtextview.setTextColor(Color.GREEN); 
linearLayout.addView(checkedtextview);
1
J Anand Boss On

Seems you are trying to add the checkedtextview twice.

To change the checked status, you can get the view from linearLayout like below

Either linearLayout.getChildAt(position) or keep a reference of checkedtextview in your class and change the status whenever you want.

2
Nikhil Sharma On

you can put check

  if (checkedtextview.getParent() == null) {
        // thn add your childview
    } else {
        linearLayout.removeAllViews();
        //add your child view herer
    }

or if you don't wanna remove all child from parent thn you can try this :

 if (checkedtextview.getParent() != null)
        ((ViewGroup)checkedtextview.getParent()).removeView(checkedtextview);
    linearLayout.addView(checkedtextview);