user1730789
user1730789

Reputation: 5177

Android insert button into a LinearLayout at Runtime

I have a linear Layout defined within my xml file as follows

   <LinearLayout
        android:id="@+id/manageStoresAlphabeticPagination"
        android:layout_width="fill_parent"
        android:orientation="horizontal"
        android:weightSum="26"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/searchBarFrameManageStores"
        android:layout_toRightOf="@+id/searchBarFrameManageStores" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="A"
            android:layout_weight="1"
            style="@style/alphaPaginationStyle" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="B"
            android:layout_weight="1"
            style="@style/alphaPaginationStyle" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="C"
            android:layout_weight="1"
            style="@style/alphaPaginationStyle" />
    </LinearLayout>

Now that content of the lineaar layout will contain all the alphabets. I dont want to define them in my layout rather through my code. How can create the button through my code, apply the style and then add it to the linear layout ?

Kind Regard

----------------EDIT--------------------------------

LinearLayout storePaginationLayout = (LinearLayout) view
                .findViewById(R.id.manageStoresAlphabeticPagination);

        for (int i = 0; i < 22; i++) {
            Button b1 = new Button(this.getActivity(), null,
                    R.style.alphaPaginationStyle);
            b1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT,1f));
            b1.setText("A");
            storePaginationLayout.addView(b1);
        }

The styles is not been applied from the code. However from the xml layout it works fine ?

Upvotes: 0

Views: 463

Answers (1)

Triode
Triode

Reputation: 11359

Button button = new Button(this, null, R.style.alphaPaginationStyle);
LinearLayout.LayoutParams params = new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(yourAlphabet);
yourLinearLayout.addView(button);

Upvotes: 1

Related Questions