Hello! The task is to redefine the TextView class so that if there is no text in it, make its background transparent. How to do it? Where to find TextView.java? Where to write code in it and how to use it in markup later? Or maybe there is some other widget that does not show the background itself if the text is empty? Need to override the setText method

  • It seems like TextView has no background and when it is empty and when it is not empty. How to make a custom View - pavlofff
  • You can find TextView.java directly in the IDE by clicking in the code editor on the mention of the TextView class and selecting "Go to -> Declaration", but if the Sources Terget API of the project was not downloaded earlier, you will be prompted to download them, and then you will see the source class. - pavlofff
  • @pavlofff, has. Otherwise I would not write. I have it in xml announced. And if I pass null into it, then padding remains - Flippy
  • I do not have an eclipse and not a studio. I'm on the phone - Flippy

1 answer 1

You need something like this:

public class MyTextView extends TextView { public MyTextView(Context context) { super(context); init(); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init(){ if (getText().length() > 0){ setBackgroundColor(Color.WHITE); }else { setBackgroundColor(Color.TRANSPARENT); } invalidate(); } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); if (text == null || text.equals("")){ setBackgroundColor(Color.TRANSPARENT); }else { setBackgroundColor(Color.WHITE); } invalidate(); } } 

I tested it when adding a TextView from the code, I think it should also work if you create it in the markup, if not, then you may need to add another attribute file.

  • tell me what makes invalidate(); ? - Silento
  • 2
    As far as I understand, this method causes a forced redraw of View - Kirill Stoianov