如何动态设置弹出窗口的linearlayout的背景?

时间:2012-12-05 08:55:49

标签: android android-linearlayout xml-drawable

我有一个弹出窗口。我想动态地将弹出窗口的LinearLayout的背景从android:background="@drawable/popup_bg"更改为android:background="@drawable/popup_bg2"

这是我的代码:

    private void showPopup(final Activity context, int x, int y, String id, String n, String a, String l) {
   int popupWidth = 200;
   int popupHeight = 150;

   // Inflate the popup_layout.xml
   LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);


   LayoutInflater layoutInflater = (LayoutInflater) context
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View layout = layoutInflater.inflate(R.layout.popup_layout, viewGroup);

  TextView id1 = (TextView) layout.findViewById(R.id.id);
  TextView name = (TextView) layout.findViewById(R.id.name);
  TextView absent = (TextView) layout.findViewById(R.id.absence);
  TextView late = (TextView) layout.findViewById(R.id.lateness);

  id1.setText(id);
  name.setText(n);
  absent.setText(a);
  late.setText(l);

   // Creating the PopupWindow
   final PopupWindow popup = new PopupWindow(context);
   popup.setContentView(layout);
   popup.setWidth(popupWidth);
   popup.setHeight(popupHeight);
   popup.setFocusable(true);

   // Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
   int OFFSET_X = 30;
   int OFFSET_Y = 300;

     // Clear the default translucent background
   popup.setBackgroundDrawable(new BitmapDrawable());

   // Displaying the popup at the specified location, + offsets.
   popup.showAtLocation(layout, Gravity.NO_GRAVITY, x + OFFSET_X, y +OFFSET_Y);

   // Getting a reference to Close button, and close the popup when clicked.
   Button close = (Button) layout.findViewById(R.id.close);
   close.setOnClickListener(new OnClickListener() {

     public void onClick(View v) {
       popup.dismiss();
     }
   });
}

popup_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:id="@+id/popup"
     android:layout_height="wrap_content"
     android:background="@drawable/popup_bg" 
     android:orientation="vertical" >
</LinearLayout>

1 个答案:

答案 0 :(得分:3)

试试这个,

     LinearLayout ll=popup.getContentView().findViewById(R.id.popup);
     ll.setBackgroundResource(R.drawable.yourImage);

在执行上述操作之前,请执行此操作popup.setContentView(layout);