2017-01-05 43 views
6

我已經寫了一個代碼來更改按鈕的最小寬度,以便我可以擺脫按鈕文本週圍的填充。不刪除按鈕文本週圍的填充

for(int i=0;i<26;i++){ 
    Button alphabet = new Button(getContext()); 
    alphabet.setText(""+(char)('A'+i)); 
    alphabet.setMinWidth(0); 
    allAlphabets.addView(alphabet); 
} 

我在每個按鈕中都有一個字母,最後將其動態添加到佈局中。由於填充,它佔用了很多空間,因爲我已將最小寬度設置爲0,但仍不起作用。它顯示相同的默認按鈕。 請幫忙。

回答

1

您必須將LayoutParams與您的Button alphabet一起應用。

+0

你能否詳細介紹一下示例代碼。 – Santanu

1

請儘量設置按鈕的填充像

Button alphabet = new Button(getContext()); 
       alphabet.setText(""+(char)('A'+i)); 
       alphabet.setPadding(0,0,0,0); 
       allAlphabets.addView(alphabet); 
+0

不工作...和以前一樣.. – Santanu

2

,你想要一個可點擊的觀點看起來像按鈕與文字

你可以做一個XML佈局與您的按鈕或裏面

一個cardview和TextView的

然後將其添加這樣的:

Button alphabetButton = LayoutInflater.from(context).inflate(R.layout.alphabet_layout); 

因此它比好代碼設計它現在是一個佈局,使您可以根據需要

,你也可以在alphabet_layout.xml

android:background="@null" 
+1

獲取無法解析的方法inflate(int) – Santanu

+0

add import android.view.LayoutInflater; – amorenew

0

添加到您的按鈕,你可以使用下面的代碼設置修改佈局:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
      LayoutParams.WRAP_CONTENT); 
button.setLayoutParams(params); 
button.setGravity(Gravity.CENTER_HORIZONTAL); 
button.setTextSize(32);