Search code examples
androidandroid-layoutandroid-relativelayoutmargins

setMargrin in Relativelayout Programmatically


I want to add a text view with margins into a Relativelayout by clicking a button, but whenever I add the setMargins to the LayoutParams, it make the TextView disappeared. Here is my code

Here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/test11">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/test"
        android:onClick="onClick"
        android:text="asdf"/>
</RelativeLayout>

Here is my code:

    public class tet extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
    }

    public void onClick(View v){
        TextView textView = new TextView(this);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        layoutParams.setMargins(30, 30, 30, 30);

        textView.setText("asdf");
        textView.setLayoutParams(layoutParams);
        ((RelativeLayout)findViewById(R.id.test11)).addView(textView);
    }
}

Solution

  • I'm 99% sure your TextView is behind your Button. There are several problems:

    layoutParams.setMargins(30, 30, 30, 30);

    This sets the margins in pixels! If you set the margins in a xml Layout they are often set as dp (you can choose the unit there). If you want dp in your code you have to convert px => dp (here you can find an example).

    Secondly: You are using an RelativeLayout, hence all Views are arranged relatively in your layout. You didn't provide any infromation to you TextView so it will be placed at the left/top of its parent (so behind your Button).

    Try swap your RelativeLayout for a LinearLayout or provide additional arrangement information.

    For the future: These kind of problems ("my view is missing") is easily solved by the Hierarchyviewer provided by the Android SDK.