添加视图后刷新 LinearLayout [英] Refreshing a LinearLayout after adding a view

查看:45
本文介绍了添加视图后刷新 LinearLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我错过了什么吗?

推荐答案

您可以在代码中检查一些事情:

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.

这个自包含的例子在短暂的延迟后添加了一个 TextView它开始:

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);
    }
}

这篇关于添加视图后刷新 LinearLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆