添加视图后刷新LinearLayout

lbe*_*gni 13 android drawable android-linearlayout

我正在尝试动态地将视图添加到线性布局.我通过getChildCount()看到视图被添加到布局中,但即使在布局上调用invalidate()也不会让我看到孩子出现.

我错过了什么吗?

Kla*_*rth 22

您可以在代码中查看以下几项内容:

这个自包含的示例在启动后的短暂延迟后添加TextView:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)