2012-01-23 3 views
0

레이아웃이있는 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 
    } 
+1

이것은 거꾸로하는 일입니다. 이 방법으로 바라는 당신의 욕망을 이해합니다 (보기 항목을 별도로 유지합니다. 이해할 수 있음) 그러나 사실은 지나치게 복잡하고 필요없는 추가 수업을 추가하는 것입니다. 귀하가 게시 한 getView에서 가져온 방법은 정확히 어떻게로드되어야하는지입니다. 뷰 자체를로드해서는 안됩니다. "컨테이너"(이 경우 컨테이너는 어댑터)는 사용중인보기를로드해야합니다. – dymmeh

+1

후속 조치로, 기술적으로 아무런 문제가 없습니다. 그것은 잘 작동합니다. 이 작업을 수행하는 것은 일반적인 관행이 아닙니다. 특히이 같은 간단한보기. – dymmeh

답변

0

나는 보통 그런 짓을. 보기가 레이아웃을로드하지 않습니다. 보기가 에서의 레이아웃으로로드됩니다. 레이아웃의 루트 요소를보기의 인스턴스로 만들려면 레이아웃에서 사용자 정의보기 태그 인 <com.mypackage.ListItem>을 사용하십시오.

+0

비록 목록 항목에 대해이 작업을 수행 한 적이 없습니다. 나는 때로는 이것을 사용자 정의 컨트롤 또는 뭔가 내부에서 수행합니다. –

+0

이전에이 솔루션을 보았지만 다른 뷰 ('ListItem') 안에 뷰 ('inflatedView')를로드하는 것은 낭비입니다. – NeilMonday

1

:

관련 문제