如何在xml中检索按钮信息

时间:2012-01-24 06:37:56

标签: android

我是android新手,我想检索XML文件中的按钮信息。 (特别是margin_top和margin_left)。之后,我想动态地为该特定按钮提供另一个边距。我可以创建具有新边距的新按钮,但我无法检索当前按钮边距..

任何帮助都将不胜感激。

android.view.ViewGroup.LayoutParams lay = btn1.getLayoutParams();

这个外层对象掌握了所有信息,但我无法从中获得利润。

我使用以下代码创建了我的按钮。

RelativeLayout layout = (RelativeLayout)findViewById(R.id.relativeTest);
        Button btn3 = new Button(TestActivity.this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        params.setMargins(200, 200, 200, 200);
        layout.addView(btn3, params);

2 个答案:

答案 0 :(得分:1)

为XML文件中的按钮指定ID,并使用 findViewById 获取该按钮,就像对RelativeLayout一样。然后,您可以获得有关该按钮的所有信息。您也可以修改按钮的属性。试试吧。

答案 1 :(得分:1)

FlaMM3R

我的布局如下所示,你必须根据你的布局使用相同的想法。

XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"            
        android:text="@string/hello"
        android:id="@+id/tv" />
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button android:id="@+id/btn"
            android:layout_width="100dip"
            android:layout_height="100dip"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="40dp"
            android:layout_marginTop="36dp"
            android:text="Button" />    
        <Button android:id="@+id/btn2"
            android:layout_width="100dip"
            android:layout_height="100dip"
            android:layout_marginLeft="148dp"
            android:layout_marginTop="62dp"
            android:text="Button"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"/>
    </RelativeLayout> 
</LinearLayout>

Java文件

public class HelloActivity extends Activity {
    TextView tv;
    Button btn;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv =(TextView)findViewById(R.id.tv);
        btn = (Button)findViewById(R.id.btn);        
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) btn.getLayoutParams();       
        tv.setText("left : "+params.leftMargin+"\ntop : "+params.topMargin);
        params.setMargins(10, 50, 0, 0); // setting new margins for btn
    }
}

在代码中使用相同的想法,让我知道发生了什么。我希望这将是你正在寻找的答案。

相关问题