繁体   English   中英

以编程方式将ImageButtons添加到ScrollView的LinearLayout

[英]Adding ImageButtons to the LinearLayout of a ScrollView programmatically

我正在尝试通过以下活动完成此任务:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MantisCharActivity">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:id="@+id/charActivityLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

使用此代码:

    TypedValue outValue = new TypedValue();
    this.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);

    LinearLayout layout = (LinearLayout) findViewById(R.id.charActivityLayout);
    String path = Environment.getExternalStorageDirectory().toString()+"/Download/TestData/";

    for (File file : folder.listFiles()) {

        ImageButton imgbut = new ImageButton(this);

        //image
        Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath() + "/00thumb.jpg");
        imgbut.setImageBitmap(myBitmap);

        imgbut.setMinimumHeight(210);
        imgbut.setAdjustViewBounds(false);
        imgbut.setBackgroundResource(outValue.resourceId);
        imgbut.setCropToPadding(false);
        imgbut.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

        layout.addView(imgbut);

活动保持完全空白。 '00thumb.jpg'文件存在,并且加载它们不会引发错误,所以那可能不是问题。 我想念什么或做错什么?

编辑:看来我的代码工作(即使它不是很优雅)。 知道发生了什么,但是我使用的模拟器出了点问题。 该应用是在我通过android studio启动时启动的,但从未更新过版本。 我在模拟器中创建了一个新设备,现在可以使用了。

做这样的事情。

    val layout = view.findViewById<LinearLayout>(R.id.yourId)
    view.layoutParams = ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layout?.addView(view)

以及添加视图及其LayoutParams之后的layout.requestLayout()

我认为问题是:无法加载图像,首先,您应该检查添加img,但是否成功:

        imgbut.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent))
        val params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            100
        )
        params.topMargin = 10
        params.bottomMargin = 10
        imgbut.layoutParams = params

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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