【发布时间】:2019-05-08 17:37:28
【问题描述】:
我正在以编程方式设置 edittext 的 x 值。但是,这样做时,调整平移功能不起作用。关于如何完成这项工作的任何想法。 activity 未处于全屏模式,这只发生在 APIs > 23 中。
例如。
Edittext editext = findViewById(R.id.edittext);
edittext.setX(200);
//现在点击edittext,如果屏幕足够低就会被软键盘覆盖
注意:setY() 也会发生这种情况
这是一个重现错误的示例:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = this;
setContentView(R.layout.activity_main);
//Get edittext from layout file and set X and Y to the bottom
//left of screen
EditText edittext = findViewById(R.id.editText);
edittext.setX(0);
//Getting device frame to make sure its below keyboard, Not
//necessary can just guess any value
edittext.setY(getDeviceFrame(context).getHeight() / 1.2f);
}
布局为:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
还有一份清单:
<activity android:name=".MainActivity"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
导致布局: Edittext after programmatic setX and setY
点击editext后,我们得到: Hidden editext
你能看到的被键盘隐藏了。
更新: 我尝试使用不同的变体来移动 EditText 仍然无济于事。
例如
edittext.animate().x(200);
更新 2: 我还没有解决这个问题。我已经越来越近了,因为我做了一些测试,似乎使用布局参数来控制视图的定位在一定程度上是有效的。
例如
ConstraintLayout.LayoutParams layoutParams =
(ConstraintLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = 200; //Your X Coordinate
layoutParams.topMargin = 200; //Your Y Coordinate
view.setLayoutParams(layoutParams);
在某种程度上,我的意思是我在测试库中弄乱了这些方法的功能,它似乎可以从 onCreate() 执行上述操作。但是,在我的应用程序中,我正在回调中进行调用。 SetX 工作正常,无需我在“post”线程或“runOnMainUI”线程中设置它。所以我不确定为什么这不起作用。
【问题讨论】:
-
欢迎来到stackoverflow。如果您发布一个可重现的最小示例,您将获得更多有用的答案,以便其他用户可以重现您的错误。
-
@Simon.S.A.感谢您的建议,我添加了代码以帮助其他人重现错误
标签: android android-activity android-edittext adjustpan setx