Expanding in Context in a ListView - Android

无人久伴 提交于 2019-12-04 21:39:13

I figure my solution will be creating my own implementation of TextView which can handle some of my requirements, but not sure if anyone has any examples I can look at..

Have a look at the class below:

public class LimitedTextView extends TextView {

    private boolean mStatus;

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Paint p = getPaint();
        String s = getText().toString();
        if (s != null && !s.equals("")) {
            int m = (int) p.measureText(s);
            if (m < getMeasuredWidth() * 2) {
                modifyParent(true);
            } else {
                modifyParent(false);
            }
        }
    }

    private void modifyParent(boolean how) {
        RelativeLayout rl = (RelativeLayout) getParent();
        rl.findViewById(R.id.minimize_maximize).setVisibility(
                how ? View.GONE : View.VISIBLE);
        if (mStatus) {
            setMaxLines(40); // arbitrary number, set it as high as possible
        } else {
            setMaxLines(2);
        }
    }

    public void storeCurrentStatus(boolean status) {
        mStatus = status;
    }

}

The LimitedTextView will measure its text using its own Paint object and test it against the measured width. If it fits on the two allowed rows it will hide the ImageView, otherwise it will show it. It also stores the current status of row(expanded/not-expanded) and increases or decreases the maximum number of lines to obtain the proper appearance. In the getView method of the adapter you would:

  • set the text
  • set the status from a boolean array according to a position(this is also required to keep the rows in order as you scroll the list):

    textView.storeCurrentStatus(mStatus[position])

  • set the OnClickListener on the LimitedTextView itself and from there update the status:

    mStatus[(Integer) v.getTag()] = !mStatus[(Integer) v.getTag()];
    notifyDataSetChanged();
    
  • based on the same mStatus boolean array you'll probably change the drawable of the ImageView, to show a different one depending on if the TextView is expanded or not

I manually wrote it, so there could be some mistakes I'm missing right now, take it as an idea. The LimitedTextView could be improved as in performance, I also don't know how well it would behave if you want to animate expanding the text.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!