我想在编程生成的TextViews之间绘制水平虚线.我试过这段代码:
Paint fgPaintSel = new Paint(); fgPaintSel.setARGB(255, 0, 0, 0); fgPaintSel.setStyle(Paint.Style.STROKE); fgPaintSel.setPathEffect(new DashPathEffect(new float[]{5, 10}, 0));
但什么都没发生.我只是复制并粘贴了这段代码.我该怎么画一条虚线?谢谢.
为活动布局指定一个ID.我使用onLlick处理程序PaintDashedLines()使用了一个按钮进行演示.
在content_main.xml布局中.
使用静态int来计算demo的目的,使用单独的方法来创建drawable,用于模块化.
在您的活动中:
static int tvCount = 0; public void PaintDashedLines(View v) { LinearLayout ll = (LinearLayout) findViewById(R.id.main); TextView tv = new TextView(MainActivity.this); tv.setGravity(Gravity.CENTER); tv.setTextSize(25); tv.setPadding(0, 5, 0, 5); ll.addView(tv); tv.setText("TextView " + tvCount); ImageView divider = new ImageView(MainActivity.this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( ll.getWidth(), 2); lp.setMargins(0, 5, 0, 5); divider.setLayoutParams(lp); divider.setBackground(CreateDashedLined()); ll.addView(divider); tvCount++; } public static Drawable CreateDashedLined() { ShapeDrawable sd = new ShapeDrawable(new RectShape()); Paint fgPaintSel = sd.getPaint(); fgPaintSel.setColor(Color.BLACK); fgPaintSel.setStyle(Paint.Style.STROKE); fgPaintSel.setPathEffect(new DashPathEffect(new float[]{5, 10}, 0)); return sd; }
-MyActivity
--int count;
--oncreate
--PaintDashedLines(View v) -
public static Drawable CreateDashedLined()
在build.gradle中(虽然这不是一成不变的)
minSdkVersion 18 targetSdkVersion 23
你不需要做任何其他事情.
在drawable文件夹中创建dotted_line.xml文件:
添加此drawable作为背景:
view.setBackground(getResources().getDrawable(R.drawable.dotted_line));
结果: