将 ImageView 添加到 LinnearLayout 会动态出错



我写了一个小函数

private void addTabIndicators(int tabCount){
    LinearLayout indicatorsContainer = (LinearLayout)findViewById(R.id.indicators_container);
    for(int i = 0; i<tabCount; i++){
        ImageView indicator = (ImageView)this.getLayoutInflater().inflate(R.layout.tab_indicator, null);
        indicatorsContainer.addView(indicator);
    }
}

这应该根据寻呼机适配器中的选项卡数量向我的活动中的线性布局添加圆圈。一切都会很酷,但是,我添加的图像视图而不是 xml 布局中声明的大小,正在调整为 1x1px......有什么想法我可能出错吗?以下是指标和线性布局的布局

tab_indicator.xml:

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="64dp"
    android:layout_height="64dp"
    android:layout_margin="8dp"
    android:src="@drawable/floating_button_background"/>

指标容器:

<LinearLayout
    android:layout_marginBottom="16dp"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/indicators_container"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</LinearLayout>

故障可能在这里

    ImageView indicator = (ImageView)this.getLayoutInflater().inflate(R.layout.tab_indicator, null);

您需要传递图像视图的根视图,以提供 XML 中定义的布局。如果改为传递 null,则会设置默认布局参数。

地方

    ImageView indicator = (ImageView)this.getLayoutInflater().inflate(R.layout.tab_indicator, your root view of image view,false);

这是一个非常常见的错误。永远不要传递空,除非你真的知道你在做什么。

在这里阅读更多内容:

http://developer.android.com/reference/android/view/LayoutInflater.html

希望对你有帮助

最新更新