如何在 Android 中透過程式設計設定 ImageView 的寬度和高度?


此示例展示瞭如何在 Android 中透過程式設計設定 ImageView 的寬度和高度

步驟 1 − 在 Android Studio 中建立新專案,轉至檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:id="@+id/rlMain"
   android:layout_height="match_parent"
   android:layout_margin="16dp" />

步驟 3 − 將以下程式碼新增到 src/MainActivity.java 中

package app.com.sample;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      RelativeLayout rlMain = findViewById(R.id.rlMain);
      ImageView imageView = new ImageView(this);
      imageView.setImageResource(R.drawable.ic_launcher_background);
      RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
         RelativeLayout.LayoutParams.MATCH_PARENT,
         RelativeLayout.LayoutParams.MATCH_PARENT
      );
      imageView.setLayoutParams(params);
      rlMain.addView(imageView);
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml 中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行你的應用程式。假設你已將 Android 移動裝置連線到計算機。要從 Android Studio 執行應用程式,請開啟專案的某個活動檔案,然後單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕 −

單擊 此處 下載專案程式碼。

更新時間:2019 年 7 月 31 日

3K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.