android - 嵌套 View 未呈现

标签 android view nested

这个网站的新手,如果这个问题不合适,或者在错误的部分,我们深表歉意。

安卓:

我编写了一个自定义按钮类,它扩展了 View 并且工作正常。现在我想创建一个数字小键盘类,它使用以特定方式排列的这些自定义按钮中的几个,然后我可以在电话拨号器应用程序中使用它们。我可以在应用程序的主要 Activity 中构建小键盘,这似乎没问题,但我想在它自己的类中构建这个小键盘以便于重复使用。当我将代码移到它自己的类中时,我得到错误或没有在屏幕上绘制。我认为部分问题是 subview 被添加到哪个类。

这是我在主要 Activity 中的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(1);
    LcarsButton numericPad[] = new LcarsButton[10]; //array of buttons

    LinearLayout rows[] = new LinearLayout[3];

    for(int i=0;i<=2;i++)
    {
        rows[i] = new LinearLayout(this);
        for(int j=1;j<=3;j++)
        {
            int k = (i * 3) + j;
            numericPad[k] = new LcarsButton(this);
            numericPad[k].label = "" + k;
            rows[i].addView(numericPad[k]); 
        }
        layout.addView(rows[i]);
    }

它循环遍历数组 numericPad,将 3 个按钮分配给每个“行”,然后将 3 个“行”分配给“布局”。这很好用。 这是在类构造函数中看到的代码:

    public class LcarsNumPad extends LinearLayout {

    public LcarsNumPad(Context context) {
    super(context);
    this.setOrientation(VERTICAL);

    LinearLayout layout = new LinearLayout(context);
    LcarsButton numericPad[] = new LcarsButton[10];


    layout.setOrientation(1);
    LinearLayout rows[] = new LinearLayout[3];

    for(int i=0;i<=2;i++)
    {
        rows[i] = new LinearLayout(context);
        for(int j=1;j<=3;j++)
        {
            int k = (i * 3) + j;
            numericPad[k] = new LcarsButton(context);
            numericPad[k].label = "" + k;
            rows[i].addView(numericPad[k]); 
        }
        layout.addView(rows[i]);
    }

如您所见,代码中的唯一区别是适应每个特定代码段的上下文。谁能告诉我哪里出错了?

最佳答案

我猜错误的原因是您正在使用 onCreate() 中定义的 layout 变量。您需要将 rows 数组传递给主要 Activity ,然后您可以从那里将其添加到布局中。

关于android - 嵌套 View 未呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11116504/

相关文章:

android - 在没有 findViewByID 的情况下访问 View ?

python - SQLAlchemy 嵌套模型创建单行

java.lang.UnsupportedClassVersionError : com/google/doclava/Doclava : Unsupported major. 次要版本 51.0 android build

android - android中的视频质量?

ruby-on-rails - 在嵌入式 ruby 中排序

java - AddView错误,只显示第一个元素

ruby-on-rails - 如何将默认值合并到 Rails 5 中的嵌套参数中?

python - 提高嵌套循环性能

Android:WAITING网络连接以进行 API 调用

android - E/内存轨道 : Couldn't load memtrack Android studio