我如何从java代码动态设置属性layout_weight在android按钮的值?
当前回答
如果你已经在layout(xml)文件中定义了你的视图,并且只想从语法上改变权重,那么创建新的LayoutParams会覆盖在xml文件中定义的其他参数。
所以首先你应该使用"getLayoutParams"然后setLayoutParams
LinearLayout。LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams(); 参数个数。重量= 4f; mButton.setLayoutParams (params);
其他回答
如果layoutparams已经定义(在XML或动态),这里有一行:
((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;
你可以把它作为LinearLayout的一部分传递进来。LayoutParams构造函数:
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
YOUR_VIEW.setLayoutParams(param);
最后一个参数是权重。
使用LinearLayout。LayoutParams:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);
编辑:啊,埃里克的答案更简单!
如果你已经在你的layout(xml)文件中定义了你的视图,只想通过编程改变权重,这种方法更好
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);
new a LayoutParams会覆盖xml文件中定义的其他参数,比如页边距,或者你需要在LayoutParams中指定所有的参数。
如果我有人在寻找答案,用这个:
LinearLayout.LayoutParams lay = (LinearLayout.LayoutParams) myLayout.getLayoutParams();
lay.weight = 0.5;
如果你从xml文件初始化布局,这将比为线性布局提供新的布局参数方便得多。
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件