【问题标题】:listView items is not match parent n linear layoutlistView 项目与父 n 线性布局不匹配
【发布时间】:2016-04-26 12:06:05
【问题描述】:

我需要创建具有 ListView 的 LinearLayout。我用这段代码做到了:

this.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    final ListView listView = (ListView) LayoutInflater.from(getContext()).inflate(R.layout.chat_timer_rollout, null);
    addView(listView);

我的聊天计时器推出是:

<ListView
xmlns:a="http://schemas.android.com/apk/res/android"
a:layout_width="match_parent"
a:layout_height="wrap_content"
a:background="@color/white"
a:cacheColorHint="@color/white"
a:paddingBottom="12dp"
a:paddingTop="12dp">

创建后,我尝试在列表视图中添加项目,如下所示:

final ArrayAdapter<TimeInterval> adapter = new ArrayAdapter<>(getContext(),
                                                                R.layout.chat_timer_item,
                                                                R.id.timer_label, TimeInterval.INTERVALS);

    listView.setAdapter(adapter);

聊天计时器项有代码:

<TextView
a:id="@+id/timer_label"
xmlns:a="http://schemas.android.com/apk/res/android"
a:layout_width="match_parent"
a:layout_height="wrap_content"
a:paddingBottom="11dp"
a:paddingLeft="@dimen/timer_label_margin_right"
a:paddingTop="11dp"
a:textColor="@color/primary_text"
a:textSize="@dimen/timer_text_size"/>

创建后,我在屏幕上看到我的线性布局,但是当我单击项目时,它具有宽度 wrap_content,与父级不匹配?如何解决?我尝试为使用参数 match_parent 膨胀设置一个线性布局,但它没有帮助。谢谢!

【问题讨论】:

  • inflate()调用中的第二个参数改为this,并移除addView()调用。
  • @MikeM.非常感谢

标签: android listview


【解决方案1】:

LayoutInflater#inflate() 方法中的第二个参数是膨胀布局的(可选)父 View。当您为父级传递null 时,Inflater 不知道哪种类型的LayoutParams 是合适的,因此它使用默认的ViewGroup.LayoutParams,这两个维度都有ViewGroup.WRAP_CONTENT

由于您发布的代码在您的LinearLayout 子类中,您可以将this 作为inflate() 调用中的第二个参数传递。此外,当您在该双参数方法中提供父 View 时,膨胀的布局会自动添加到其中,因此您不需要 addView() 调用。

final ListView listView = (ListView) LayoutInflater.from(getContext())
    .inflate(R.layout.chat_timer_rollout, this);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    相关资源
    最近更新 更多