Pas*_*ein 21 android position runtime absolutelayout
如果你使用AbsoluteLayout(我知道它已被弃用,但这是解决我问题的唯一方法)你可以给childViews标签android:layout_x并android:layout_y设置它们的绝对位置AbsoluteLayout.
但是我不想在xml中设置这些信息,因为我只在运行时知道它们.那么如何在运行时以编程方式设置这些参数呢?我没有在View上看到任何方法view.setLayoutX(int x)或类似的东西.
这是我的XML,当我设置layout_x和layout_y值时,它工作正常:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="@drawable/myImageView"
android:layout_width="1298px"
android:layout_height="945px"
android:layout_x="0px"
android:layout_y="0px" />
<Button
android:id="@+id/myButton1"
android:text="23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50px"
android:layout_y="300px"
android:tag="23"/>
<Button
android:id="@+id/myButton2"
android:text="48"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50px"
android:layout_y="300px"
android:tag="48"/>
</AbsoluteLayout>
Run Code Online (Sandbox Code Playgroud)
实际上,我不想再在xml中设置任何按钮,而是通过远程检索一些信息并根据该信息添加按钮.
这是我正在使用的代码部分,所以在我onCreateMethod添加这些按钮:
for (MyRemoteObject remoteObject: list) {
Button button = new Button(this);
button.setOnClickListener (listener);
button.setTag(remoteObject.id);
button.setText(remoteObject.id);
// button.setLayoutX(remoteObject.x) ????
// button.setLayoutY(remoteObject.y) ????
myLayout.addView(button);
}
Run Code Online (Sandbox Code Playgroud)
Che*_*mon 14
使用带有LayoutParams的addView版本:
LayoutParams params = mLayout.generateLayoutParams();
params.x = remoteObject.x;
params.y = remoteObject.y;
mLayout.addView(button, params);
Run Code Online (Sandbox Code Playgroud)
Amp*_*y91 10
在回答你对Mayra答案的评论时,我遇到了与RelativeLayout而不是AbsoluteLayout类似的问题.解决方案是使用类似的方法并将其转换为布局类型.像这样的东西:
LayoutParams params = (android.widget.RelativeLayout.LayoutParams) this.generateDefaultLayoutParams();
params.height = 360;
params.width = 360;
params.addRule(CENTER_IN_PARENT);
this.addView(board, params);
Run Code Online (Sandbox Code Playgroud)
我花了很长时间才想到这一点,所以如果他们需要,我想在这里发布给别人.
小智 5
我遇到了同样的问题,但发现了一个不同的解决方案.
int width = 100, height = 50, x = 10, y = 20;
Button button = new Button(this);
AbsoluteLayout myLayout = (AbsoluteLayout)findViewById(R.id.myLayout);
myLayout.add(button, new AbsoluteLayout.LayoutParams(width, height, x, y));
Run Code Online (Sandbox Code Playgroud)
如果您找到"fill_parent"使用的内容(提示尝试-1),那么您可以将这些常量用于宽度和高度.