向线性布局添加 1 像素高度的视图会导致按钮停止工作

Adding a 1 pixel height view to Linear Layout causes Buttons to stop working

我已经扩展了一个 LinearLayout,我正在使用下面的代码在其中制作一个类似网格的按钮结构

TypedValue outValue = new TypedValue();
    mContext.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);

    for(int currentRow=1; currentRow<=5; ++currentRow) {
        LinearLayout horizontalLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1);
        horizontalLayout.setLayoutParams(layoutParams);
        horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);

        if (currentRow!=1) {
            View horizontalLine = new View(mContext);
            LinearLayout.LayoutParams horizontalLineParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
            horizontalLine.setLayoutParams(horizontalLineParams);
            horizontalLine.setBackgroundColor(0xff000000);
            horizontalLayout.addView(horizontalLine);
        }

        for(int currentColumn=1; currentColumn<=3; ++currentColumn) {
            Button button = new Button(mContext);
            LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1);
            button.setLayoutParams(buttonParams);
            button.setBackgroundResource(outValue.resourceId);
            button.setId(currentColumn + (currentRow - 1) * mPatternSize.numberOfColumns);
            button.setOnClickListener(this);
            horizontalLayout.addView(button);

            if (currentColumn!=mPatternSize.numberOfColumns) {
                View verticalLine = new View(mContext);
                LinearLayout.LayoutParams verticalLineParams = new LinearLayout.LayoutParams(1, ViewGroup.LayoutParams.MATCH_PARENT);
                verticalLine.setLayoutParams(verticalLineParams);
                verticalLine.setBackground(new ColorDrawable(0xff000000));
                horizontalLayout.addView(verticalLine);
            }
        }

        this.addView(horizontalLayout);
    }

在这种情况下,第一个 'if' 块是有问题的块,只要它为真,它就会导致按钮消失,但分隔符仍然有效。我该怎么办?

在我的activity中,这个LinearLayout定义为

<me.rijul.knockcode.KnockCodeButtonView
    android:id="@+id/knockCodeView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="vertical" />

在过去的 4 个小时里,我一直在尝试解决这个问题,但我一无所获。感谢您花时间帮助我。

按钮消失是因为您在水平 LinearLayout 中插入了一个宽度为 MATCH_PARENT 的视图,因此它占据了布局的整个宽度:

  ...
  horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
  if (currentRow!=1) {
        View horizontalLine = new View(mContext);
        LinearLayout.LayoutParams horizontalLineParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
  ...