给活动布局一个id。我在这个演示中使用了一个按钮和一个 onclick 处理程序 PaintDashedLines()。
在 content_main.xml 布局中。
<LinearLayout android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" .../>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="PaintDashedLines"
android:text="Press Me"/>
</LinearLayout>
出于演示的目的,使用静态 int 进行计数,并使用单独的方法来创建可绘制对象,以实现模块化。
在你的活动中:
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;
}
-我的活动
--int 计数;
--oncreate
--PaintDashedLines(查看 v)
--public static Drawable CreateDashedLined()
在 build.gradle 中(虽然这不是一成不变的)
minSdkVersion 18
targetSdkVersion 23
您无需执行任何其他操作。