这段代码如何工作?

时间:2013-10-13 08:54:38

标签: android listview view baseadapter

我从教程中编写了这段代码。

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    // TODO Auto-generated method stub
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.single_row, viewGroup,false);

    TextView title = (TextView) row.findViewById(R.id.txtTitle);
    TextView description = (TextView) row.findViewById(R.id.txtDescription);
    ImageView image = (ImageView) row.findViewById(R.id.imgPic);

    SingleRow temp = list.get(i);

    title.setText(temp.title);
    description.setText(temp.description);
    image.setImageResource(temp.image);


    return row;
}

在这行代码中:

TextView title = (TextView) row.findViewById(R.id.txtTitle);

我认为TextView被复制到同一类型的变量中。然后在这行代码中:

title.setText(temp.title);

我们用某些东西填充该变量。然后返回一个视图的行变量,它与'title'变量无关 这个怎么运作?我认为这些变量与此无关。

3 个答案:

答案 0 :(得分:0)

这是用于返回列表视图中某行的视图的方法。 row变量实际上与title相关,您可以在此处看到.-

TextView title = (TextView) row.findViewById(R.id.txtTitle);

换句话说,titleTextView内部row对象,该代码检索它以设置其文本。总而言之,整个getView方法正在膨胀single_row View,并为row的所有相关子项设置属性。

答案 1 :(得分:0)

View row = inflater.inflate(R.layout.single_row, viewGroup,false);

您正在为布局single_row

进行充气
TextView title = (TextView) row.findViewById(R.id.txtTitle);

初始化singlerow.xml

中的textview
title.setText(temp.title);

将标题设置为textview。

您正在为listview中的每一行设置布局。

最好使用viewHolder模式。

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

此外,您可以将以下内容移动到适配器类的构造函数,并将inflater声明为类成员

 inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

您可能会对以下链接感兴趣

How ListView's recycling mechanism works

答案 2 :(得分:0)

此代码会膨胀新视图,设置其内容。这意味着您以编程方式创建新视图。它经常被使用,即在填充列表时,您将拥有行数,每个行的结构相同,但值不同。

以下是它的工作原理:

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    // Get the inflater service
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Inflate view with ID = R.layout.single_row into the row variable
    View row = inflater.inflate(R.layout.single_row, viewGroup,false);

    // Get child views of row: title, description and image.
    TextView title = (TextView) row.findViewById(R.id.txtTitle);
    TextView description = (TextView) row.findViewById(R.id.txtDescription);
    ImageView image = (ImageView) row.findViewById(R.id.imgPic);

    // This get's some template view which will provide data: title, description and image
    SingleRow temp = list.get(i);

    // Here you're setting title, description and image by using values from `temp`.
    title.setText(temp.title);
    description.setText(temp.description);
    image.setImageResource(temp.image);

    // Return the view with all values set. This view will be later probably added somewhere as a child (maybe into a list?)
    return row;
}