简体   繁体   中英

How to set ImageButton size and when button is pressed show it on added image

Here is the code i am using to create ImageButton. All my buttons will be created dynamically.

        //It is button which inherits from ImageView
        ImageButton button = new ImageButton(this);

        Drawable testPic = getResources().getDrawable(R.drawable.test_pic);

        //button.setBackgroundColor(R.color.transparent_background);//transparent image button button background

        //button.setImageDrawable( testPic ); 
        button.setBackgroundDrawable(testPic);

        //button.setMaxWidth(20);

        button.setOnClickListener(mCorkyListener);
        button.setTag(i);
        //button.setId(i);

        //Controls how the image should be resized or moved to match the size of this ImageView. 
        button.setScaleType( ScaleType.CENTER_INSIDE );

        System.out.println("button with "+button.getMeasuredWidth());
        System.out.println("button height "+button.getMeasuredHeight());

First of all my System.out return button with 0 and button height 0 but on device i see that it is bigger than i want, I put this button into Scrollview:

LinearLayout pubLayout = (LinearLayout)findViewById( R.id.myFilesScrollerLayout);

pubLayout.addView( button );

<ScrollView
    android:id="@+id/myFilesScroller"
    android:layout_width="200dp"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"

     >

    <LinearLayout
        android:id="@+id/myFilesScrollerLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

So how to change my ImageButton size depending maybe on ScrollView size. Also how to show that button is pressed ?

Thanks.

Try this

Drawable dr = getResources().getDrawable(R.drawable.somedrawable); Bitmap bitmap = ((BitmapDrawable) dr).getBitmap(); // Suppose you want to set the size as 50x50 Drawable d = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, 50, 50, true));

You can also use drawable.setBounds(0, 0, 50, 50);. But there are scenarios it may not work for some imageviews. Try using both.

For checking if the button is pressed, use selector & item in your xml. THIS LINK may help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM