Android setLayoutParams不起作用的原因之一

一个父节点下的所有子空间的VISIBLE属性必须都是可见的,不能有

android:visibility="gone"这种代码,否则调用setLayoutParams就会无效
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用 Android 中的 Canvas 和 Paint 类来实现该功能。具体实现步骤如下: 1. 在 xml 布局文件中添加一个自定义 View,如下所示: ``` <com.example.gridview.Gridview android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/gridview"/> ``` 2. 创建一个继承自 View 的类 Gridview,重写 onDraw 方法,在该方法中绘制田字格,代码如下: ``` public class Gridview extends View { private int mWidth, mHeight; private Paint mPaint; public Gridview(Context context) { this(context, null); } public Gridview(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Gridview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mPaint = new Paint(); mPaint.setColor(Color.BLACK); mPaint.setStrokeWidth(2); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidth = getMeasuredWidth() / 8; mHeight = getMeasuredHeight() / 8; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 绘制横向线 for (int i = 0; i <= 8; i++) { canvas.drawLine(0, i * mHeight, mWidth * 8, i * mHeight, mPaint); } // 绘制纵向线 for (int i = 0; i <= 8; i++) { canvas.drawLine(i * mWidth, 0, i * mWidth, mHeight * 8, mPaint); } } } ``` 3. 在 Activity 中获取该自定义 View 并添加到布局中,如下所示: ``` Gridview gridview = findViewById(R.id.gridview); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.START | Gravity.TOP; gridview.setLayoutParams(params); ``` 运行程序,即可看到在屏幕的左上方绘制了一个屏幕八分之一大小的田字格。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄油奥特曼

如果可以,请我喝一杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值