【问题标题】:ImageButton Position programmatically以编程方式定位 ImageButton
【发布时间】:2014-01-01 13:49:23
【问题描述】:

我使用 XML 进行布局,但我需要以编程方式定位 ImageButton。谁能告诉我怎么做?

XML

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainScreenLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView 
android:id="@+id/mainScreenImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerCrop"
android:src="@drawable/screenimage"/>

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/titleview"
android:background="#00000000"
android:adjustViewBounds="true"
android:src="@drawable/buttonstart"/>

</FrameLayout>

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @Nizam 我尝试了 1)Rudra 在下面通过将 AbsoluteLayout 更改为 FrameLayout 但无法编译,2)尝试了 setBoundsInScreen(Rect) 但我不知道如何正确使用它所以无法编译跨度>

标签: android xml layout imagebutton


【解决方案1】:

首先,用 FrameLayout 将 ImageButton 包装成

....
<FrameLayout
    android:id="@+id/frameLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/titleview"
android:background="#00000000"
android:adjustViewBounds="true"
android:src="@drawable/buttonstart"/>

</FrameLayout>
....

这不是必须的,是一个FrameLayout。 只需用一些布局包装图像。但对于其他布局,X 和 Y 的定位会有所不同。

现在,我可以将 ImageButton 的位置更改为,

FrameLayout mFrame=(FrameLayout) findViewById(R.id.frameLayout1);
mFrame.setPadding(fromLeftX, fromTopY, fromRight, fromBottom);

【讨论】:

  • 不客气。作为新用户,您可能不知道您可以通过单击上面的勾号来接受此答案。新年快乐
【解决方案2】:

我认为 LayoutParams 可以正常工作 试试这个代码

    Button button = (Button)findViewById(R.id.my_button);
    AbsoluteLayout.LayoutParams absParams = 
        (AbsoluteLayout.LayoutParams)button.getLayoutParams();
    absParams.x = myNewX;
    absParams.y = myNewY;
    button.setLayoutParams(absParams);

如果你想在上面设置图像,请使用 setBackgroundResources 属性

    button.setBackgroundResource(R.drawable.new_image);

【讨论】:

  • 你知道如何在 FrameLayout 中做到这一点吗?
  • 绝对布局参数已弃用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多