java - 如何设置 ImageButton 大小以及按下按钮时将其显示在添加的图像上

标签 java android

这是我用来创建 ImageButton 的代码。我的所有按钮都将动态创建。

        //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());

首先,我的 System.out 返回 按钮为 0,按钮高度为 0 但在设备上我发现它比我想要的大,我将此按钮放入 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>

那么如何根据 ScrollView 的大小来更改 ImageButton 的大小。另外如何显示按钮已按下?

谢谢。

最佳答案

试试这个

Drawable dr = getResources().getDrawable(R.drawable.somedrawable); 位图 bitmap = ((BitmapDrawable) dr).getBitmap(); //假设你想将尺寸设置为50x50 Drawable d = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, 50, 50, true));

您还可以使用drawable.setBounds(0, 0, 50, 50);。但在某些情况下,它可能不适用于某些 ImageView 。尝试同时使用两者。

要检查按钮是否被按下,请在 xml 中使用选择器和项目。 THIS LINK可能有帮助

关于java - 如何设置 ImageButton 大小以及按下按钮时将其显示在添加的图像上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10443443/

相关文章:

java - 错误的符号引用。 WebUI.class 中的签名引用了包 org 中的术语 eclipse,该术语不可用

android - 构建应用程序时 Gradle 错误

android - 为什么jetpack compose海拔会夹住我的影子?

java - WSDL 操作中的soapAction 属性为空

java - ListView 为空时无法添加和编辑单元格

java - 编写 JUnit 测试用例的最佳规则

java - 您必须使用@NonNull 注释主键吗?

java - Spring全局事务

Android:监听状态栏通知

android - 在 Android 中为 ProgressBar 添加图标