jas*_*son 3 java android paint android-layout
我想在编程生成的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));
Run Code Online (Sandbox Code Playgroud)
但什么都没发生.我只是复制并粘贴了这段代码.我该怎么画一条虚线?谢谢.
为活动布局指定一个ID.我使用onLlick处理程序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>
Run Code Online (Sandbox Code Playgroud)
使用静态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;
}
Run Code Online (Sandbox Code Playgroud)
-MyActivity
--int count;
--oncreate
--PaintDashedLines(View v) -
public static Drawable CreateDashedLined()
在build.gradle中(虽然这不是一成不变的)
minSdkVersion 18
targetSdkVersion 23
Run Code Online (Sandbox Code Playgroud)
你不需要做任何其他事情.
在drawable文件夹中创建dotted_line.xml文件:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:left="-3px"
android:right="-3px"
android:top="-3px">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2px"
android:color="@color/dark_blue"
android:dashGap="2px"
android:dashWidth="3px" />
</shape>
</item>
</layer-list>
Run Code Online (Sandbox Code Playgroud)
添加此drawable作为背景:
view.setBackground(getResources().getDrawable(R.drawable.dotted_line));
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
4031 次 |
| 最近记录: |