레이아웃이있는 ListItem
을 호출하는 사용자 정의 View 서브 클래스가 있습니다 (res/layout/list_item.xml
). 내 ListItem
클래스에서 레이아웃 xml 파일을로드 할 수 없습니다.View 서브 클래스가 자신의 레이아웃을로드하도록 지시하는 방법
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
클래스 내에서 레이아웃을로드 할. 뷰가 자체 레이아웃을로드 할 수 있습니까? 당신은 거꾸로있어
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
}
이것은 거꾸로하는 일입니다. 이 방법으로 바라는 당신의 욕망을 이해합니다 (보기 항목을 별도로 유지합니다. 이해할 수 있음) 그러나 사실은 지나치게 복잡하고 필요없는 추가 수업을 추가하는 것입니다. 귀하가 게시 한 getView에서 가져온 방법은 정확히 어떻게로드되어야하는지입니다. 뷰 자체를로드해서는 안됩니다. "컨테이너"(이 경우 컨테이너는 어댑터)는 사용중인보기를로드해야합니다. – dymmeh
후속 조치로, 기술적으로 아무런 문제가 없습니다. 그것은 잘 작동합니다. 이 작업을 수행하는 것은 일반적인 관행이 아닙니다. 특히이 같은 간단한보기. – dymmeh