java - 即使在应用解决方法后 getWidth() 也会返回 0
问题描述
我的java代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
final TextView textView = (TextView) findViewById(R.id.text1);
final Button button = (Button) findViewById(R.id.button1);
button.post(new Runnable() {
@Override
public void run() {
int buttonWidth = button.getWidth();
int textWidth = textView.getWidth();
button.setWidth(buttonWidth-textWidth);
}
});
我的 xml 视图:
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Timer"
android:textSize="16sp"/>
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="+5"/>
我正在使用this answer中描述的第二种方式。
我想要做的是让按钮填充整个宽度,并为 textView 提供足够的空间。我最近几个月一直在学习 Android,所以如果你能以清晰的方式解释它会很有帮助。
解决方案
使用 addOnGlobalLayoutListener 代替您链接的解决方案,当我看到这个问题时,这通常对我有用。
myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > 16) {
myView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
myView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
myView.getWidth();
}
});
推荐阅读
- python - 返回与中心节点间接相关的所有节点
- python - 生命值降至 0 后,敌人将不可见 - 如何解决?
- sql - 日期时间格式的日期数据的累积计数
- ruby-on-rails - Ruby on Rails:“显示”帐户路径
- reactjs - 我在 gh-pages 中的反应应用程序只显示 read.me 而不是 index.js;
- javascript - 禁止在整个项目 HTML 页面中拖动图像
- python - 尝试安装 python-language-server 时出现“错误:命令‘gcc’失败,退出状态为 1”
- python - 循环通过保存在数据框中的sql查询?
- java - 按位运算 && 溢出
- c++ - LeetCode 问题 #22 如何调试递归问题?