代码:
package zhangphil.test;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
public class TestActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_activity);
Button mButton = findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
show(mButton, 0, 0);
}
});
}
private void show(View view, int xOff, int yOff) {
View contentView = LayoutInflater.from(getApplicationContext()).inflate(android.R.layout.simple_list_item_2, null, false);
contentView.setBackgroundColor(Color.LTGRAY);
TextView text1 = contentView.findViewById(android.R.id.text1);
text1.setText("zhang");
TextView text2 = contentView.findViewById(android.R.id.text2);
text2.setText("phil");
float[] size = getDeviceDisplaySize(getApplicationContext());
PopupWindow window = new PopupWindow(contentView, (int) size[0], 300, true);
//window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
window.setOutsideTouchable(true);
window.setTouchable(true);
window.showAsDropDown(view, xOff, yOff);
}
public static float[] getDeviceDisplaySize(Context context) {
Resources resources = context.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
float[] size = new float[2];
size[0] = width;
size[1] = height;
return size;
}
}
运行如图: