处理自定义视图中的布局

发布于 2024-12-23 02:46:27 字数 941 浏览 4 评论 0原文

我制作了一个自定义视图来满足我对以简单方式显示数学向量的需求。 我扩展了 LinearLayout 并为值添加了 ArrayList。每次值更改时,我都会调用自定义方法 redraw() 将 EditText 添加到 LinearLayout。这样,在添加值后,所有现有的 EditText 都会再次添加。如何清除 LinearLayout 或显示新的 LinearLayout?

这里有一些代码:

public Vector(Context context, AttributeSet attrs) {
    super(context, attrs);
    setWillNotDraw(false);
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (inflater != null) {
        inflater.inflate(R.layout.vector, this);
    }
}

public void redraw() {
    for (Float value : getArray()) {
        EditText edit = new EditText(getContext());
        edit.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.FILL_PARENT));
        edit.setText(value.toString());

        ((LinearLayout) findViewById(R.id.root)).addView(edit);
    }
}

I made a custom view to satisfy my need for an easy way to display a mathematic vector.
I extended a LinearLayout and added an ArrayList for the values. Everytime the values change I call my custom method redraw() to add EditTexts to the LinearLayout. This way after adding a value, all existing EditTexts are added once again. How to I clear the LinearLayout or display a new LinearLayout?

Here some code:

public Vector(Context context, AttributeSet attrs) {
    super(context, attrs);
    setWillNotDraw(false);
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (inflater != null) {
        inflater.inflate(R.layout.vector, this);
    }
}

public void redraw() {
    for (Float value : getArray()) {
        EditText edit = new EditText(getContext());
        edit.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.FILL_PARENT));
        edit.setText(value.toString());

        ((LinearLayout) findViewById(R.id.root)).addView(edit);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

も让我眼熟你 2024-12-30 02:46:27

您可以使用 ((LinearLayout) findViewById(R.id.root)).removeAllViews() 删除所有视图。
但是,如果您可以为现有编辑文本视图设置新值并仅在仍然需要时添加新视图,那么为什么要重新添加所有编辑文本呢?
我没有完全理解你。

You can remove all views by using ((LinearLayout) findViewById(R.id.root)).removeAllViews().
But why do you want to add all the edit text all over again if you can set the new values to the existing edit text views and add new view only if you still need to.
I didn't fully understand you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文