添加视图之后刷新的LinearLayout视图、LinearLayout

2023-09-13 00:14:37 作者:有些关系不过期

喜    我想动态添加意见到的LinearLayout。 我通过getChildCount(),该意见被添加到布局看,但即使调用无效()上的布局不给我孩子的出现了。

Hi 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.

我缺少的东西?

推荐答案

一对夫妇的事情,你可以检查你的code:

A couple of things you can check in your code:

在视图将被加入,检查是否调用它的setLayoutParameter方法用合适的ViewGroup.LayoutParameter. 当你添加新的视图 S,确保你正在做它的UI线。要做到这一点,你可以使用父视图的post方法 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);
    }
}