[英]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.