Android Application

Kotlin 이미지뷰(ImageView)

작성자 임베디드코리아 작성일23-09-18 00:39 조회2,358회 댓글0건
-------------------------------------------------------------------------------------
      activity_main.xml
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/layout"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="200dp"
        android:text="Add Image" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/sunup" />

</RelativeLayout>

-------------------------------------------------------------------------------------
    MainActivity.kt
-------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val imageView = ImageView(this)
        // setting height and width of imageview
        imageView.layoutParams= LinearLayout.LayoutParams(400, 400)
        imageView.x= 200F // setting margin from left
        imageView.y= 200F // setting margin from top

        // accessing our custom image which we added in drawable folder
        val imgResId = R.drawable.poppy_flowe
        var resId = imgResId

        // button onClick listener
        val button = findViewById<Button>(R.id.button)
        button.setOnClickListener{
            imageView.setImageResource(resId)
        }

        // accessing our relative layout from activity_main.xml
        val layout = findViewById<RelativeLayout>(R.id.layout)

        // Add ImageView to LinearLayout
        layout?.addView(imageView) // adding image to the layout
    }
}
-------------------------------------------------------------------------------------
    AndroidManifest.xml
-------------------------------------------------------------------------------------
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>