如何告诉View子类加载自己的布局

时间:2012-01-23 22:01:07

标签: android

我有一个自定义的View子类,我调用它ListItem,它有一个布局(res/layout/list_item.xml)。我无法让我的ListItem类加载布局xml文件。

public class ListItem extends View{

    private TextView title, subtitle;

    public ListItem(Context context) {
        this(context, null);
    }

    public ListItem(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ListItem(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        //I want to load/inflate the view here so I can set title and subtitle.
    }
}

我可以通过这样做来加载视图,但我不喜欢它发生在ListItem类范围之外的事实。好像ListItem应该负责加载自己的视图。来自ListViewAdapter.java:

public View getView(int position, View convertView, ViewGroup parent) {
    ListItem entry = items.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_item, null);
    }

    TextView title = (TextView) convertView.findViewById(R.id.title);
    title.setText(entry.getTitle());

    TextView subtitle = (TextView) convertView.findViewById(R.id.subtitle);
    subtitle.setText(entry.getSubtitle());

    return convertView; 
}

同样,我想从ListItem类中加载布局。视图是否可以加载自己的布局?

2 个答案:

答案 0 :(得分:1)

你倒退了。视图不会加载 a 布局;从布局加载视图。如果您希望布局的根元素是视图的实例,请在布局中使用自定义视图标记:<com.mypackage.ListItem>

答案 1 :(得分:0)

我通常会这样做:

public ListItem(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View inflatedView = inflater.inflate(R.layout.list_item, this);

        TextView title = (TextView) inflatedView .findViewById(R.id.title);
        title.setText(entry.getTitle()); // entry needs to be available
        TextView subtitle = (TextView) inflatedView .findViewById(R.id.subtitle);
        subtitle.setText(entry.getSubtitle()); // entry needs to be available
    }