Android: How to make AlertDialog with 2 Text Lines

2019-02-15 18:55发布

问题:

How to make a List Dialog with rows like this:

|-----------------------------|
| FIRST LINE OF TEXT      (o) | <- this is a "RadioButton"
| second line of text         |
|-----------------------------|

I know I should use a custom adapter, passing a row layout with those views (actually, I've made this). But the RadioButton does not get selected when I click on the row.

Is it possible that the dialog manage the radiobuttons it self?

回答1:

I've found solutions here and here.

Basically, we have to create a "Checkable" layout, because the view's root item must implement the Checkable interface.

So I create a RelativeLayout wrapper that scans for a RadioButton and voilá, the magic is done.

public class CheckableLayout extends RelativeLayout implements Checkable
{
    private RadioButton _checkbox;

    public CheckableLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate()
    {
        super.onFinishInflate();
        // find checkable view
        int childCount = getChildCount();
        for (int i = 0; i < childCount; ++i)
        {
            View v = getChildAt(i);
            if (v instanceof RadioButton)
            {
                _checkbox = (RadioButton) v;
            }
        }
    }

    public boolean isChecked()
    {
        return _checkbox != null ? _checkbox.isChecked() : false;
    }

    public void setChecked(boolean checked)
    {
        if (_checkbox != null)
        {
            _checkbox.setChecked(checked);
        }
    }

    public void toggle()
    {
        if (_checkbox != null)
        {
            _checkbox.toggle();
        }
    }

}

You can do it with Checkbox or whatever you need.