开发者

onPrepareDialog ListView not populating on first Alert Dialog Creation

开发者 https://www.devze.com 2023-04-04 08:44 出处:网络
I create an alert dialog that has a basic checkbox list in it when I press a button. If the items have been checked before, I want to be able to check the checkboxes for the user.I have accomplished t

I create an alert dialog that has a basic checkbox list in it when I press a button. If the items have been checked before, I want to be able to check the checkboxes for the user. I have accomplished this by manipulating "onPrepareDialog" like so:

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
 Log.v("dialog", "On prepare dialog");  
 ListView lv = ((AlertDialog) dialog).getListView();


    if (lv == null){
        return;
    }
开发者_Go百科
    String[] names = Utility.convertStringToArr(currentTravelers, ", ");
    for(int i = 0;i < lv.getChildCount();i++){

        for(int j = 0;j< names.length;j++){
            String tn = lv.getItemAtPosition(i).toString();
            if(tn.equalsIgnoreCase(names[j])){
                lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                 lv.setItemChecked(i, true);
            }
        }
    }
}

This works fine, EXCEPT for the very first time I select the button. It will just show me the checklist with nothing selected. If I cancel out and hit it again, I will then see the correct names checked. I've tried tracing out the ListView child count, and it comes up as 0 the first time.

Is there anyway around this so that the very first time the alert dialog comes up it actually populates the listview so I can check the correct names?

Is there something I am not overriding or adapting? I am at a loss here.

Thanks!


Well I was able to get around this by putting a post delay before it populates the listview:

Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     public void run() { //code to manipulate goes here
}}, 100);

This basically makes it wait 100 milliseconds, which seems to be enough time for the dialog information to load into the listview. Does anyone know a more efficient way of doing this?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号