-1

我只使用 Java 代码创建了布局设计,而不是来自 XML 布局设计。我使用的代码如下

 public View getView(int position, View convertView, ViewGroup parent) {
  TextView tv = new TextView(mContext);
  tv.setText(hotelList.get(position).name);
  return tv;
  }

如何使用 layoutInflator 来创建布局。我需要在单个列表项中再添加 2 个文本视图。整个列表包含 10 个不同的列表项

请为此提供一些代码。帮助表示赞赏

4

3 回答 3

2

I have gone through this before by having my static class too. Check this out, it will help:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;


        if ( rowView == null) {

            LayoutInflater inflator = this._activity.getLayoutInflater();
            rowView = inflator.inflate(R.layout.todolistlisting, null);
            TodoListViewHolder viewHolder = new TodoListViewHolder();
            viewHolder._name        = (TextView) rowView.findViewById(R.id.tVTLName);           
            viewHolder._completed   = (TextView) rowView.findViewById(R.id.tVTLCCount);
            viewHolder._remaining   = (TextView) rowView.findViewById(R.id.tVTLRCount);
            rowView.setTag(viewHolder);

        }

        TodoListViewHolder holder = (TodoListViewHolder) rowView.getTag();
        VO_TodoList votodolist = this._items.get(position);         
        holder._name.setText(votodolist._title);            
        holder._completed.setText(votodolist._completed);
        holder._remaining.setText(votodolist._remaining);

        return rowView;     

    }

TodoListViewHolder is my view component holder here. like your TextView.

于 2012-04-03T12:08:20.827 回答
2

我猜你知道如何为这个布局制作 XML 布局。因此,只需使用以下代码制作 XML 布局并获取主布局的对象:

LinearLayout mainLayout=(LinearLayout) View.inflate(R.layout.yourlayout); //if yourlayout.xml is the name of the xml file you made and put in the layout folder.

要获取布局的孩子,假设它是TextView带有 id 的text,那么代码将是:

TextView textView=(TextView)mainLayout.findViewById(R.id.text);
于 2012-04-03T06:51:42.047 回答
0

您可以像这样使用 inflater 在运行时添加视图

LinerLayout linearLayout = (LinearLayout)inflater.inflate(R.layout.news_categories_item, null);

TextView categoryValueTextView = (TextView)linearLayout.findViewById(R.id.news_category_item_value);

mMainLinearLayout.addView(categoryValueTextView);

在这里,我在运行时膨胀另一个线性布局中存在的一个文本视图(这是仅包含文本视图的简单线性布局),并将其添加到我的主要线性布局中。

您可以使用 getLayoutInflater() 在您的活动中获取充气对象。如果你想在适配器中获得充气机,你必须将充气机对象从你的活动传递给适配器的构造函数。

于 2012-04-03T06:57:14.497 回答