Search code examples
androidandroid-layoutandroid-custom-view

How to add TextView to custom LinearLayout view?


I created a custom view that extends LinearLayout. I'm adding them to the screen through a Service like this:

WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(view, mParams);

This works for a simple empty view with just a background color. But now I want to add TextViews, and I'm trying this:

TextView tv = new TextView(this);
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tv.setText("Test text");
view.addView(tv);

However the TextViews aren't showing. What am I missing?

EDIT: I just noticed that the TextView is drawn if I remove this overrided method on the custom view:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDesiredWidth(), getDesiredHeight());
    }

However, I need that line to properly set the size I want for the views.


Solution

  • I'd personsally go down the inflation route, as have had headaches in the past caused by programmatically adding views. Here's a quick example of a custom view that's extended from LinearLayout, inflated from an XML layout file, with a public method for setting the value of the embedded textview.

    The key bit is this:

    private TextView embeddedTextView;
    
    ..
    
    private void init() {
    
        LayoutInflater.from(getContext()).inflate(
                R.layout.linear_layout_with_textview_layout, this);
    
        embeddedTextView = (TextView) findViewById(R.id.embedded_text_view);
    
    }
    
    public void setEmbeddedTextViewText(String text) {
    
        embeddedTextView.setText(text);
    }
    

    I take this approach as you swap out different styled layouts in XML and use the same Custom View; proper code re-usability. Less work in the long-run.

    Edit: Here's a way of hiding the textview by default, or an empty string "".