我的 Android 屏幕下部有一个 EditText,如图所示。由于一些项目限制,我应该只使用绝对定位。
单击 EditText 时,软键盘会隐藏 EditText,如另一幅图像所示。
我尝试将 android:windowSoftInputMode="adjustResize" 放入清单文件中(也尝试过 adjustmentPan) 它仅适用于相对定位(下面注释了 textField_layoutparams 代码),但似乎不适用于绝对定位。
甚至尝试放置 ScrollView (下面注释了代码),但它不起作用。
代码:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val scrollView: ScrollView
val relativeLayout: RelativeLayout
val textField: EditText
/*scrollView = ScrollView (this)
scrollView.layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
)*/
//scrollView.isFillViewport = true
//setContentView(scrollView)
relativeLayout = RelativeLayout(this)
relativeLayout.layoutParams = RelativeLayout.LayoutParams (
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
)
relativeLayout.setBackgroundColor(Color.parseColor("#0000FF"))
//scrollView.addView(relativeLayout)
setContentView (relativeLayout)
textField = EditText(this)
val textField_layoutparams: LayoutParams
textField_layoutparams = RelativeLayout.LayoutParams (
400,
150
)
textField.setBackgroundColor(Color.parseColor("#FFFFFF"))
//textField_layoutparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE)
//textField_layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
//textField_layoutparams.setMargins(0, 0, 0, 200)
textField.layoutParams = textField_layoutparams
textField.hint = "Enter Text"
textField.x = 500F
textField.y = 2200F
relativeLayout.addView(textField)
}
/**
* A native method that is implemented by the 'scrollviewpoc' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'scrollviewpoc' library on application startup.
init {
System.loadLibrary("scrollviewpoc")
}
}
}
在绝对定位的情况下有什么方法可以实现所需的行为吗?
我认为当您尝试从 Kotlin 端设置
EditText
x 和 y 时会产生该问题。
android:windowSoftInputMode="adjustResize"
中的属性Manifest.
适用于所有Android设备,但在您的情况下,我看到您以编程方式设置X和Y的区别。
你应该尝试一下这个。我希望它对你有用
override fun onCreate(){
// ...
relativeLayout.addView(textField) // your last line add bellow of that code
val rootView = findViewById<View>(android.R.id.content)
rootView.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
val heightDiff = rootView.height - relativeLayout.height
if (heightDiff > 100) { // Adjust this threshold according to your needs
// Soft keyboard is shown
val newTopMargin = 2200 - heightDiff
textField_layoutparams.topMargin = newTopMargin
textField.layoutParams = textField_layoutparams
} else {
// Soft keyboard is hidden
textField_layoutparams.topMargin = 2200
textField.layoutParams = textField_layoutparams
}
return true
}
})
}