簡體   English   中英

Android以編程方式添加的按鈕具有匹配的父級寬度和高度

[英]Android programmatically added button has match parent width and height

我正在嘗試添加此按鈕

        Button dalsi_akce = new Button(this);
        dalsi_akce.setGravity(Gravity.CENTER);
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
        dalsi_akce.setLayoutParams(p);
        setContentView(dalsi_akce);
        dalsi_akce.setText("test");

按鈕出現,但是完全匹配的父對象。 我在整個顯示器上都有這個按鈕。 如何設置按鈕的寬度和高度?

您正在將活動的內容設置為按鈕。 這就是為什么它涵蓋了整個活動並且是錯誤的。

而是創建活動的布局(xml文件)並使用setContentView設置。 然后,您可以以編程方式向內容添加按鈕。

例:

您的活動:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ViewGroup viewGroup = (ViewGroup) findViewById(R.id.myLayout);
    Button dalsi_akce = new Button(this);
    dalsi_akce.setGravity(Gravity.CENTER);
    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    dalsi_akce.setLayoutParams(p);
    dalsi_akce.setText("test");


    viewGroup.addView(dalsi_akce);
}

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/myLayout"
    tools:context=".MyActivity">


</RelativeLayout>

首先,您應該將內容視圖定義為RelativeLayout或LinearLayout,然后將按鈕添加到此布局。 您也可以使用RelativeLayout.LayoutParams類的另一個構造函數:

RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(200, 70);

實際上,您使用此構造函數:

public LayoutParams(int w, int h) {
    super(w, h);
}

如果您只是在layout.xml中創建布局,然后根據需要在代碼中自定義按鈕,則會更容易。 例如,您可以執行以下操作:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

  <Button
  android:id"@+id/left_button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentTop="true"
  android:layout_alignParentRight="true"
  android:text="Left"/>

</RelativeLayout>

這將為您提供一個按鈕,其大小僅與右上角的內容一樣大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM