相对布局位置以编程方式

时间:2013-06-21 22:02:27

标签: android relativelayout

我正在尝试使用相对布局添加不同的视图。 edittext和微调器被添加但列表视图没有显示。另外,我没有使用xmls进行布局

public class CustomView extends LinearLayout {
    Context rContext;
    private String rTitle;

    private Spinner rSpinner;
    private EditText rInput;
    private ListView rResultsList;

    public CustomView(Context context) {
        super(context);
        rContext = context;
    }

    public CustomView(Context context, AttributeSet attrs, int theme) {
        super(context, attrs, theme);
    }

    public void initialize(String title) {

        rTitle = title;
        rInput = new EditText(rContext);
        rInput.setId(1);
        rSpinner = new Spinner(rContext);
        rSpinner.setId(2);
        rResultsList = new ListView(rContext);
        rResultsList.setId(3);
        rInput.setText("1");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(rContext, R.layout.result_item, R.id.result_item, new String[] { "this", "that" });
        rResultsList.setAdapter(adapter);
        addViews();
    }

    @Override
    public String toString() {

        return rTitle;
    }

    private void addViews() {

        RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(ConvertoActivity.APP_WIDTH / 2, 100);
        relativeParams.addRule(RelativeLayout.RIGHT_OF, rInput.getId());

        RelativeLayout.LayoutParams relativeParams2 = new RelativeLayout.LayoutParams(ConvertoActivity.APP_WIDTH / 2, 100);
        relativeParams.addRule(RelativeLayout.LEFT_OF, rSpinner.getId());

        RelativeLayout.LayoutParams relativeParams3 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        relativeParams.addRule(RelativeLayout.BELOW, rInput.getId());

        this.addView(rInput, relativeParams2);
        this.addView(rSpinner, relativeParams);
        this.addView(rResultsList, relativeParams3);


    }
}

enter image description here

2 个答案:

答案 0 :(得分:0)

您的自定义视图扩展了LinearLayout,您正在使用RelativeLayout.Layout参数。更改自定义视图以扩展RelativeLayout。

答案 1 :(得分:0)

没关系,我找到了答案。 我正在为相对参数的相同对象添加规则。