如何在android中的两个按钮之间绘制垂直线

时间:2013-09-23 17:23:53

标签: android

我有一个简单的线性布局。我正在通过代码一下方添加按钮,其间有一些空格。我需要在这两个按钮之间画一条垂直线(特定的垂直箭头线)。

请您告诉我如何从button1的按钮到按钮2的顶部绘制一条垂直线。

我使用DrawLine()绘制一条线,但它在button2下面绘制了一些偏移量。

这是我的代码:

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class SampleMethodActivity extends Activity {
    Button b,b1;
    public int width,height,bottom;
     LinearLayout ll;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_method);

        ll = (LinearLayout) findViewById(R.id.my_linear_layout);


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 12, 0, 40);

        b = new Button(this);
        b.setText("This is a sample text");

        b.setLayoutParams(params);
        b.setGravity(Gravity.CENTER);
        ll.addView(b);


        b1 = new Button(this);
        b1.setText("This is a sample text to chck the width and height of a button1 and need to check how long it gets stretched and to check the width");
        b1.setLayoutParams(params);
        b1.setGravity(Gravity.CENTER);
        ll.addView(b1);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        width = b.getWidth();
        height = b.getHeight();
        bottom = b.getBottom();

        DrawView dv = new DrawView(this,width/2,bottom);
        ll.addView(dv);

     }
}

下面是DrawView类:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class DrawView extends View {
    Paint paint = new Paint();
    int x,y;

    public DrawView(Context context,int x,int y) {
        super(context);
        this.x=x;
        this.y=y;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(3);
        System.out.println("X: "+x);
        canvas.drawLine(x, y, x, y+400, paint);
    }

}

2 个答案:

答案 0 :(得分:5)

使用视图绘制线条

如果您只需要直线水平或垂直线,那么最简单的方法可能是在xml布局文件中使用View。你会做这样的事情:

<View
    android:layout_width="1dp"
    android:layout_height="match_parent"
    android:background="@android:color/black" />

设置第一个按钮gravity to left和其他to right,然后在它们之间添加一个视图并将其设置为gravity to center

第二种方式

添加按钮(重量45)视图(10)按钮2(重量45),您就完成了。 你也可以创建一个xml并将其膨胀为LinearLayout。

垂直线宽为1dp,水平线高为1dp

答案 1 :(得分:0)

将此添加到colors.xml

<color name="streat_line">#D0D5D8</color>

将此应用于您想要创建行的位置

<TextView
android:id="@+id/TextView"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:background="@color/streat_line" >
相关问题