0

我想将 TextView 插入到 LinearLayout 中,该文件位于另一个 XML 文件中,该文件用作 ListView 的布局。但似乎我无法访问其他 XML 文件中的 LinearLayout。

我运行一个获取类别标题的循环,并且对于每个标题,我想创建一个带有标题的 TextView。

我如何插入 TextView

LinearLayout Layout = (LinearLayout) findViewById(R.id.itemDesign); //When debugging I can see "Layout" is just null. itemDesign is also not in main.xml.
TextView title = new TextView(this);
title.setText(CatName);
Layout.addView(title);

ListView“single_list_item.xml”使用的XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/itemDesign"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Name Label -->
    <TextView android:id="@+id/name_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="25dip"
        android:textStyle="bold"
        android:paddingTop="10dip"
        android:paddingBottom="10dip"
        android:textColor="#43bd00"/>
    <!-- Description Label -->
    <TextView android:id="@+id/email_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#acacac"/>
</LinearLayout>
4

4 回答 4

1

听起来你需要夸大你的观点。在getView()适配器类中

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.your_layout, parent, false);

然后访问你TextView

TextView firstTV = (TextView) rowView.findViewById(R.id.some_id);

关于 LayoutInflater

于 2013-02-19T15:37:55.493 回答
0

我猜,您在使用之前没有设置活动内容视图findViewById()

setContentView(R.layout.myLayout);

之后初始化您的文本视图,并为其添加宽度、高度参数。然后将该文本视图添加到布局中应该没有问题。

于 2013-02-19T15:16:24.327 回答
0

也许您应该在添加 TextView 后尝试使布局无效:

Layout.addView(title);
Layout.invalidate();

我仍然不完全确定你想要实现什么,也许你可以给我们一些关于你想要完成的更多信息?

于 2013-02-19T15:24:05.813 回答
0

如果你想基于一个xml文件新建一个ListView项,你需要先inflate它。然后你可以调用findViewById()结果视图来获取孩子。

LayoutInflater inf = LayoutInflater.from(getContext());
LinearLayout listItemLayout = (LinearLayout)inf.inflate(R.layout.single_list_item, null);

TextView nameLabel = (TextView) listItemLayout.findViewById(R.id.name_label);
于 2013-02-19T15:38:37.283 回答