Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing a LinearLayout after adding a view

I'm trying to add views dynamically to a linearlayout. I see through getChildCount() that the views are added to the layout, but even calling invalidate() on the layout doesn't give me the childs showed up.

Am I missing something?

like image 473
lbedogni Avatar asked Mar 18 '10 11:03

lbedogni


1 Answers

A couple of things you can check in your code:

  • On the View that is being added, check that you call its setLayoutParameter method with an appropriate ViewGroup.LayoutParameter.
  • When you adding the new Views, make sure you are doing it on the UI thread. To do this, you can use the parent View's post method.

This self contained example adds a TextView after a short delay when it starts:

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ProgrammticView extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final LinearLayout layout = new LinearLayout(this);
        layout.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT));

        setContentView(layout);

        // This is just going to programatically add a view after a short delay.
        Timer timing = new Timer();
        timing.schedule(new TimerTask() {

            @Override
            public void run() {
                final TextView child = new TextView(ProgrammticView.this);
                child.setText("Hello World!");
                child.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));

                // When adding another view, make sure you do it on the UI
                // thread.
                layout.post(new Runnable() {

                    public void run() {
                        layout.addView(child);
                    }
                });
            }
        }, 5000);
    }
}
like image 78
Klarth Avatar answered Sep 29 '22 15:09

Klarth