如何在 Android 按鈕上以程式設計方式設定 drawableLeft?
本示例演示如何在 Android 中以程式設計方式設定 drawableleft。
步驟 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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button/DrawableLeft" android:layout_centerInParent="true" android:drawableStart="@drawable/ic_brush" android:textSize="24sp" android:textStyle="bold"/> </RelativeLayout>
步驟 3 − 向 src/MainActivity.java 中新增以下程式碼。
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
Drawable img = button.getContext().getResources().getDrawable( R.drawable.ic_brush );
button.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);
}
}步驟 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 執行應用程式,請開啟一個專案活動檔案,然後點選工具欄中的執行
圖示。選擇移動裝置作為選項,然後檢查將顯示預設介面的移動裝置 -

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP