我如何从java代码动态设置属性layout_weight在android按钮的值?
当前回答
我已经通过添加这行代码完成了我的任务!
LinearLayout.LayoutParams mylayout = (LinearLayout.LayoutParams)
myview.getLayoutParams();
mylayout.weight = 2;
myview.setLayoutParams(mylayout);
其他回答
我已经通过添加这行代码完成了我的任务!
LinearLayout.LayoutParams mylayout = (LinearLayout.LayoutParams)
myview.getLayoutParams();
mylayout.weight = 2;
myview.setLayoutParams(mylayout);
如果我有人在寻找答案,用这个:
LinearLayout.LayoutParams lay = (LinearLayout.LayoutParams) myLayout.getLayoutParams();
lay.weight = 0.5;
如果你从xml文件初始化布局,这将比为线性布局提供新的布局参数方便得多。
您可以尝试这种方法。 首先,您获得与此按钮关联的LayoutParams。执行类型转换。
LinearLayout.LayoutParams linearLayoutParams = (LinearLayout.LayoutParams) button.getLayoutParams();
然后分配所需的“weight”参数值。
linearLayoutParams.weight = 5;
重新绘制布局。
button.requestLayout();
任何线性布局。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)
}
}
推荐文章
- 如何使梯度背景在android
- 列出一个Intent的所有附加项
- Android中使用的SQLite版本?
- 如何获得转轮价值?
- 在Wireshark上捕获手机流量
- 为开发设置设备(????????????)没有权限)
- 如何使用XML更改ActionBarActivity的ActionBar的背景颜色?
- 从Android模拟器访问localhost:端口
- Android应用程序中的“包”是什么
- 如何从代码中动态设置layout_weight属性?
- 更新列表后,滚动到列表的末尾
- Android Toast可以比Toast. length_long长吗?
- 如何从资源设置位图
- 是否有可能在线性布局的宽度上均匀分布按钮
- 我如何禁用方向改变在Android?