Search code examples
javaandroidviewmargin

Android set margin of view programmatically


I wanted to set margin to View programmatically. Here is my XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llAttendeeList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" 
android:background="#000000">

 <ListView
    android:id="@+id/attendeelistview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"     
    android:listSelector="#F6CECE" >
</ListView>

</LinearLayout>

And the method when my button onClick to call out the popup Window view:

private void openPopUp() {
    LayoutInflater layoutInflater = (LayoutInflater) getActivity()
            .getBaseContext().getSystemService(
                    context.LAYOUT_INFLATER_SERVICE);
    View popupView = layoutInflater.inflate(R.layout.event_attendee_pop,
            null);
    llAttendeeList = (LinearLayout) popupView
            .findViewById(R.id.llAttendeeList);
    attendeeListView = (ListView) popupView.findViewById(R.id.attendeelistview);


    LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
    params.setMargins(10, 10, 10, 0);
    popupView.setLayoutParams(params);

    final PopupWindow popupWindow = new PopupWindow(popupView,
            LayoutParams.WRAP_CONTENT, 350);
    popupWindow.setOutsideTouchable(true);
    popupWindow.setBackgroundDrawable(new BitmapDrawable());

    popupWindow.setTouchInterceptor(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                popupWindow.dismiss();
                return true;
            }
            return false;
        }
    });
    popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
    mAdapter = new ListAdapter(getActivity());
    attendeeListView.setAdapter(mAdapter);
}

I tried to set margin to the popupView but no luck. The margin is not there. I wonder which part override it.


Solution

  • Manually set width and height of PopupWindow :

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    
    popupWindow.setWidth(width-10);
    popupWindow.setHeight(height-10);