动态添加时不显示自定义视图

Custom View Not Showing When Dynamically Added

这里不知所措。到处搜索,找不到这个问题的答案...

我有一个 XML 布局,其中有一个相对布局,我将其用作不同视图的占位符。

<RelativeLayout
    android:id="@+id/relVariableLayoutPlaceHolder"

    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"

    android:background="@color/white"
    >

</RelativeLayout>

在我的 activity 中,我有一个供用户按下的按钮,当他们按下它时,我希望创建并动态添加自定义 ClockView。请注意 _variableLayoutonCreate 方法中完美设置:

public void onStartTimeClick(View view)
{
    //Clean up any left over views
    _variableLayout.removeAllViews();

    //Add clock view
    ClockView clockView = new ClockView(_context);
    _variableLayout.addView(clockView);
}

问题是按下按钮时,屏幕上没有任何反应。我可以,但是当我点击也在屏幕上的 TextView 时看到它。

我在这里上传了一些点击TextView之前和之后的图片: http://imgur.com/a/9lebv

我想这与绘制时钟视图后屏幕未刷新有关,但我已经尝试了我能想到的 invalidate()requestLayout() 的所有组合。有什么想法吗?

您尝试设置 LayoutParams 了吗?

public void onStartTimeClick(View view)
{
    //Clean up any left over views
    _variableLayout.removeAllViews();

    //Add clock view
    ClockView clockView = new ClockView(_context);
    RelativeLayout.LayoutParams layout_params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    clockView.setLayoutParams(layout_params);
    _variableLayout.addView(clockView);
}

出于历史原因,我觉得我应该提一下,经过大量调试后我发现我的问题出在 ClockViewonMeasureonLayout 函数中。基本上它们的格式很差,并且没有正确测量子视图以使 onLayout 函数正确处理。

一旦我解决了这些问题,一切都按预期工作。