我的任務是生成幾個固定寬度和高度的按鈕。我決定將這些按鈕存儲在某個ArrayList中以供將來使用。這就是我要做的事:如何在這種情況下將Button充氣到LinearLayout?
for(int i = 1 ; i<=n; i++)
{
Button place = new Button(this.context) ;
place.setTextColor(ContextCompat.getColor
(this.context,R.color.background_color));
place.setTypeface(typefaceForPlaces);
place.setId(i+0);
place.setBackgroundResource(R.drawable.real_place_background);
place.setLayoutParams(new
LinearLayout.LayoutParams(65,65));
places.add(place);
}
但問題是在這裏 place.setLayoutParams(newLinearLayout.LayoutParams(65,65));
這裏,寬度和高度以像素爲單位設置。但我需要dp
。我知道 將dp轉換爲像素的代碼,但我不認爲這是很好的解決方案。現在,我有一個想法來創建一些佈局,並在那裏存儲我的按鈕的形狀。這裏是我的佈局對該被叫place_button.xml
:
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/real_place_background"
android:textColor="#202020">
</Button>
我創造了一些View
和膨脹該按鈕這一觀點。之後,我通過它的id獲得了上面的按鈕,並將它保存到另一個按鈕,因爲我需要很多這樣的按鈕。然後我需要改變新的按鈕的ID。但我得到了以下錯誤:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.incubic.abay.clasico/com.incubic.abay.clasico.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setId(int)' on a null object reference
下面是我的代碼:
private void generatePlaces() {
View place_view = LayoutInflater.from(getContext()).inflate(R.layout.place_button,null);
for(int i = 1 ; i<=n; i++)
{
Button place = (Button)place_view.findViewById(R.id.button_id);
place.setId(i+0);
place.setTypeface(typefaceForPlaces);
places.add(place) ;
}
}
一切都發生在片段。 generatePlaces
方法在onViewCreated
之後調用。如何解決我的問題?
在place_button.xml中是否有一個「button_id」作爲id的元素? –
@AbhishekPatel是的。更新的問題。謝謝 – abay
我並沒有忘記添加id,實際上。無論如何,這個錯誤。 – abay