Jim*_*nts 6 xml android android-drawable
我正在初始化一个带有图标(国家/地区标志)和电话号码的下拉菜单。前缀(字符串)。当我在 XML 中设置 drawable 时,它可以工作:
app:drawableStartCompat="@drawable/flag_afn"
Run Code Online (Sandbox Code Playgroud)
但是当我以编程方式找到视图时,使用
setCompoundDrawablesWithIntrinsicBounds
Run Code Online (Sandbox Code Playgroud)
它不起作用。
主活动.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewGroup =
(findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0) as ViewGroup
initializeSpinner(viewGroup)
}
private fun initializeSpinner(parent: ViewGroup) {
ArrayAdapter.createFromResource(
this,
R.array.phone_country_codes,
R.layout.spinner_dropdown_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item)
// Apply the adapter to the spinner
phonePrefix.adapter = adapter
for (cnt in 0 until adapter.count) {
val drawable = ContextCompat.getDrawable(this, R.drawable.flag_bmd)
val view = adapter.getView(cnt, null, parent) as AppCompatTextView
view.text = "TEST"
// view.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null)
// view.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
view.setCompoundDrawablesWithIntrinsicBounds(R.drawable.flag_bmd, 0, 0,0)
}
}
}
Run Code Online (Sandbox Code Playgroud)
活动_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<Spinner
android:id="@+id/phonePrefix"
android:layout_width="180dp"
android:layout_height="40dp"
android:layout_margin="8dp" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
spinner_dropdown_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView 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:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:maxLength="4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="inherit"
tools:text="+31"
app:drawableStartCompat="@drawable/flag_afn" />
Run Code Online (Sandbox Code Playgroud)
phone_country_codes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="phone_country_codes">
<item>+31</item>
<item>+49</item>
<item>+41</item>
</string-array>
</resources>
Run Code Online (Sandbox Code Playgroud)
此屏幕截图显示了“+31”而不是“TEST”以及添加到 xml 中的标志。