我如何从java代码动态设置属性layout_weight在android按钮的值?
当前回答
任何线性布局。LayoutParams和TableLayout。LayoutParams对我有用,对于按钮右边的是taberlow。LayoutParams。那就是:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
关于使用MATCH_PARENT或WRAP_CONTENT是相同的。
其他回答
如果我有人在寻找答案,用这个:
LinearLayout.LayoutParams lay = (LinearLayout.LayoutParams) myLayout.getLayoutParams();
lay.weight = 0.5;
如果你从xml文件初始化布局,这将比为线性布局提供新的布局参数方便得多。
如果layoutparams已经定义(在XML或动态),这里有一行:
((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;
任何线性布局。LayoutParams和TableLayout。LayoutParams对我有用,对于按钮右边的是taberlow。LayoutParams。那就是:
TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1f);
关于使用MATCH_PARENT或WRAP_CONTENT是相同的。
使用Kotlin你可以做以下事情:
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.widget.*
import android.widget.LinearLayout
class RespondTo : CardView {
constructor(context: Context) : super(context) {
init(context)
}
private fun init(context: Context) {
val parent = LinearLayout(context)
parent.apply {
layoutParams = LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT, 1.0f).apply {
orientation = LinearLayout.HORIZONTAL
addView(EditText(context).apply {
id = generateViewId()
layoutParams = LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 0.9f).apply {
}
})
addView(ImageButton(context).apply({
layoutParams = LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 0.1f)
background = null
setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_save_black_24px))
id = generateViewId()
layoutParams = RelativeLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT).apply {
addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
// addRule(RelativeLayout.LEFT_OF, myImageButton.id)
}
}))
}
}
this.addView(parent)
}
}
如果你想设置权重为线性布局,然后使用下面提到的代码或设置权重为相对布局,然后将其替换为相对布局
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
); YOUR_VIEW.setLayoutParams (param);
推荐文章
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败