android - How to inflate Button to LinearLayout progmatically in this case? -
my task generate several amount of buttons fixed width , height.i decided store these buttons in arraylist use in future. how it:
for(int = 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 here place.setlayoutparams(newlinearlayout.layoutparams(65,65));
here,width , height set in pixels. need dp
. know code converts dp pixels, not think solution. now,i have idea create layout , store there button's shape. here layout 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 created view
, inflated button view. after that, got button above id , save button,because need lot of such buttons. needed change new button's id. got following error:
java.lang.runtimeexception: unable start activity componentinfo{com.incubic.abay.clasico/com.incubic.abay.clasico.gameactivity}: java.lang.nullpointerexception: attempt invoke virtual method 'void android.widget.button.setid(int)' on null object reference
below code:
private void generateplaces() { view place_view = layoutinflater.from(getcontext()).inflate(r.layout.place_button,null); for(int = 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 called after onviewcreated
. how solve problem?
probably have issue due absence of button
id
<?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"/>
update:
when inflation, button view, no need findviewbyid.
in general don't think inflating view in case approach. better create buttons:
private void generateplaces() { (int = 1; <= 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(dptopx(50), dptopx(50))); places.add(place); } } private int dptopx(int dp) { return (int) (dp * resources.getsystem().getdisplaymetrics().density); }
Comments
Post a Comment