如何将自定义视图膨胀为本身?

How do I inflate a custom view as itself?

我在 ArrayAdapter 中使用自定义视图 (RouteView) 并尝试在此处使用自定义视图,以便我可以对对象执行一些逻辑操作,但出于某种原因,它似乎隐形!我可以与之互动,但什么也看不见。

这是我的 RouteView class:

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。有谁知道我在这里做错了什么?

谢谢!

是的,正如@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
}

或者不要重写这个方法