My task is to generate several amount of buttons with fixed width and height.I decided to store these buttons in some ArrayList to use in the future. This is how I do it:
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);
}
But problem is here
place.setLayoutParams(newLinearLayout.LayoutParams(65,65));
Here,width and height is set in pixels. But I need dp
. I know code that
converts dp to pixels, but I do not think that it is good solution. Now,I have an idea to create some layout and store there my button's shape. Here is my layout for this called 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>
And I created some View
and inflated that button to this view. After that, I got the button above by its id and save it to another button,because I need a lot of such buttons. Then I needed to change new button's id. But i got following error:
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
Below is my code:
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) ;
}
}
Everything happens in Fragment. generatePlaces
method is called after onViewCreated
. How to solve my problem?