Android自定义按钮(xml)通过代码添加

时间:2016-10-25 09:35:51

标签: android xml

我的视图看起来像这样 -

<View
            android:layout_width="match_parent"
            android:layout_height="@dimen/line"
            android:background="#000000"></View>

        <Button
            android:id="@+id/button13"
            android:layout_width="match_parent"
            android:layout_height="@dimen/button_height"
            android:background="@drawable/border"
            android:drawableLeft="@mipmap/ic_launcher"
            android:text="Button" />

我想使用JAVA代码将其添加到我的活动中。 我尝试手动完成

LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    Button btn = new Button(this);
    btn.setText("hello");

    int size = (int)getResources().getDimension(R.dimen.button_height);

    View line = new View(this);
    LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int)getResources().getDimension(R.dimen.line));
    line.setLayoutParams(lparams);
    line.setBackgroundColor(Color.BLACK);
    layout.addView(line);


    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, size);
    btn.setLayoutParams( params);
    btn.setBackground(getResources().getDrawable(R.drawable.border));
    layout.addView(btn);

但是我不能输入0.1dp值作为线的高度。如何将这个xml代码添加到java上的活动中?

1 个答案:

答案 0 :(得分:0)

请试一试。

linearLayout = (LinearLayout) findViewById(R.id.ll_parent);
        Button btn = new Button(this);
        btn.setText("hello");

        View line = new View(this);
        LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,10);
        line.setLayoutParams(lparams);
        line.setBackgroundColor(Color.BLACK);
        linearLayout.addView(line);


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 120);
        btn.setLayoutParams( params);

        btn.setBackgroundColor(Color.GRAY);
        linearLayout.addView(btn);