如何将自定义视图自身充气?

时间:2015-09-28 01:08:51

标签: java android android-custom-view

我在RouteView中使用自定义视图(ArrayAdapter)并尝试在此处使用自定义视图,因此我可以对该对象执行某些逻辑,但由于某种原因,它似乎隐形!我可以与它互动,但没有任何东西可见。

这是我的RouteView课程:

public class RouteView extends RelativeLayout {

public RouteView(Context context){
    super(context);
    init();
}
private void init(){

    inflate(getContext(), R.layout.route_item, this);
}
public void setFrom(String fromText){
    TextView from = (TextView) findViewById(R.id.from);
    from.setText(fromText);
}
public void setTo(String toText){
    TextView to = (TextView) findViewById(R.id.to);
    to.setText(toText);
}
public RouteView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {

}

以下是我如何构建它:

private class RoutesAdapter extends ArrayAdapter{
    public RoutesAdapter(Context context, int resource, ArrayList<Route> objects) {
        super(context, resource, objects);
    }

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

        RouteView v;
        if(convertView == null){
            v = new RouteView(getContext());
        } else {
            v = (RouteView) convertView;
        }

        Route route = (Route) getItem(position);
        v.setFrom(route.getFrom());
        v.setTo(route.getTo());

        return v;
    }
}

我的XML根元素是<merge>元素RelativeLayout。有谁知道我在这里做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

是的,@ kingfisher-phuoc说你的:

@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {

}

尝试调用super:

 @Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
    super.onLayout(b, i, i1, i2, i3);
    ... //your code
}

或者不要覆盖此方法