Android Material Design:ListPopupWindow



Android Material Design:ListPopupWindow


Android Material Design引入的ListPopupWindow,首先是一个PopupWindow,不过此PopupWindow内嵌一个List,给予此List设置一个Adapter,就相当Android为开发者做好了一个内置ListView的PopupWindows。

如图所示:

Android Material Design:ListPopupWindow_第1张图片


给出上述效果的代码实现:

package zhangphil.materialdesign;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.ListPopupWindow;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		final Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupWindow(button);
			}
		});
	}

	public void showListPopupWindow(View view) {
		String items[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
		ListPopupWindow listPopupWindow = new ListPopupWindow(this);

		// ListView适配器
		listPopupWindow.setAdapter(
				new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));

		// 选择item的监听事件
		listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView parent, View view, int pos, long id) {
				Toast.makeText(getApplicationContext(), "选择:" + pos, Toast.LENGTH_SHORT).show();
				// listPopupWindow.dismiss();
			}
		});

		// 对话框的宽高
		listPopupWindow.setWidth(500);
		listPopupWindow.setHeight(600);

		// ListPopupWindow的锚,弹出框的位置是相对当前View的位置
		listPopupWindow.setAnchorView(view);

		// ListPopupWindow 距锚view的距离
		listPopupWindow.setHorizontalOffset(50);
		listPopupWindow.setVerticalOffset(100);

		listPopupWindow.setModal(false);

		listPopupWindow.show();
	}
}

activity_main.xml只是一个仅仅含有一个Button的布局,Button用于触发、弹出ListPopupWindow,不在此赘述。

你可能感兴趣的:(Android,Android新概念设计,android)