如何在 Android 中以程式設計方式設定背景 drawable?
本示例演示如何在 Android 中以程式設計方式設定背景 drawable。
步驟 1 − 在 Android Studio 中建立一個新專案,轉到 File ⇒ New Project 然後填寫所有必需資訊以建立一個新專案。
步驟 2 − 向 res/layout/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" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/rl" tools:context=".MainActivity"> <Button android:text="Set Drawable" android:id="@+id/btnSetDrawable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="10dp"/> </RelativeLayout>
步驟 3 − 向 src/MainActivity.java 中新增以下程式碼。
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity { Button button; RelativeLayout relativeLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); relativeLayout = findViewById(R.id.rl); button = findViewById(R.id.btnSetDrawable); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { relativeLayout.setBackgroundResource(R.drawable.image); } }); } }
步驟 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 執行應用程式,請開啟專案的一個活動檔案,然後單擊工具欄中的執行圖示 。選擇你的移動裝置作為一個選項,然後檢視你的移動裝置,它將顯示你的預設螢幕 -
點選 此處 下載專案程式碼。
廣告