![](/img/trans.png)
[英]JFrame getWidth() and getHeight() return 0 even after pack()
[英]getWidth() returns 0 even after applying a workaround
我的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"/>
我正在使用此答案中所述的第二種方法。
我想做的是讓按鈕用足夠的空間填充整個寬度以容納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();
}
});
您可以將線性布局與權重為1的按鈕和textview一起使用以包裝內容。
嘗試這個:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="some text" />
</LinearLayout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.