Android弹窗中的spinner异常解决办法

弹窗常用AlertDialog来袜,因为AlertDialog可以很方便的添加所要的项。比如确定/取消按钮,自定义的标题栏、自定义的信息布局等。在自定义布局时,比如我们采用LinearLayout来布局,然后再往LinearLayout中添加一些项,比如TextView、EditText等。这些都很容易实现。

不过,如果添加spinner,可能就会出问题了。找了很久,发现是context引起的。因为spinner在点击展开下拉列表时,需要依赖于窗体,而使用context只是提供了一个上下文,并没有提供窗体,所以会造成错误。下面是已实现的代码:

package com.sparkle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

public class Contury {

	private Activity _activity = null;
	private Context _context = null;
	private Spinner _spinner = null;

	public Contury(Activity activity) {
		_activity = activity;
		_context = activity;
	}

	private LinearLayout GenerateLinearLayout(int orientation) {
		LinearLayout linearLayout = new LinearLayout(_context);
		linearLayout.setPadding(16, 16, 16, 16);
		linearLayout.setOrientation(orientation);
		return linearLayout;
	}

	@SuppressWarnings("deprecation")
	private Spinner GenerateSpinner() {
		Spinner spinner = new Spinner(_activity);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		spinner.setLayoutParams(layoutParams);
		return spinner;
	}

	public void Popup() {
		Builder alertDialogBuilder = new AlertDialog.Builder(_activity);
		View view = GenerateLayout();
		alertDialogBuilder.setView(view);
		alertDialogBuilder.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.e("TEST","OK");
					}
				});
		alertDialogBuilder.setNegativeButton("Cancel", null);
		Dialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}

	private View GenerateLayout() {
		LinearLayout linearLayout = GenerateLinearLayout(LinearLayout.VERTICAL);

		LinearLayout messageLinearLayout = GenerateMessageLayout();

		linearLayout.addView(messageLinearLayout);

		return linearLayout;
	}

	private LinearLayout GenerateMessageLayout() {
		LinearLayout linearLayout = GenerateLinearLayout(LinearLayout.HORIZONTAL);
		_spinner = GenerateSpinner();
		_spinner.setAdapter(new CityAdapter(_activity));
		_spinner.setSelection(0);
		linearLayout.addView(_spinner);
		return linearLayout;
	}	

	private class CityAdapter extends BaseAdapter implements SpinnerAdapter {

		private Context _con=null;
		private String[] _cities=null;

		public CityAdapter(Context context)
		{
			_con=context;
			_cities=_con.getResources().getStringArray(
					R.array.cities);
		}

        @Override
        public int getCount() {
        	if(_cities==null)
        	{
        		return 0;
        	}
            return _cities.length;
        }

        @Override
        public Object getItem(int position) {
        	if(_cities==null||_cities.length<=0)
        	{
        		return null;
        	}
            return _cities[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textView=new TextView(_con);
			textView.setTextColor(Color.BLACK);
			textView.setTextSize(20);
			textView.setText(_cities[position]);
			return textView;
		}

    }

}

注:

1、spinner和AlertDialog的new需使用activity,使用context将在弹出下拉菜单时造成错误。

2、_con.getResources().getStringArray(R.array.cities)是加载xml中定义的数组。

city.xml(位于values文件夹下)

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="cities">
        <item>厦门</item>
        <item>北京</item>
        <item>上海</item>
    </string-array>

</resources>
时间: 2024-08-06 23:22:14

Android弹窗中的spinner异常解决办法的相关文章

android 开发中遇到错误及解决办法总结

新手总结的开发中所遇到错误及解决办法,如有不对,欢迎指正,如有更好的解决办法,也请不吝赐教. 一.dialog.show()引起的android.view.WindowManager$BadTokenException错误 错误日志 android.view.WindowManager$BadTokenException: Unable to add window -- token [email protected] is not valid; is your activity running?

Android主线程不能访问网络异常解决办法

从两个方面说下这个问题: 1. 不让访问网络的原因 2. 解决该问题的办法 不让访问网络的原因: 由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会出现假死的现象,产生很不好的用户体验.所以,默认的情况下如果直接在主线程中访问就报出了这个异常,名字是NetworkOnMainThreadException 解决该问题的办法 1. 独立线程 2. 异步线程AsyncTask 3. StrictMode修改默认的策略 1) 独立线程的办法 启动一个

关于Android PopupWindow中实用Spinner控件点击APP Crash情况整理!

场景异常信息如下: android.view.WindowManager$BadTokenException: Unable to add window -- token [email protected] is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:646) at android.view.WindowManagerGlobal.addView(Wi

配置Android环境遇到的问题及解决办法

配置Android环境遇到的问题及解决办法: 1 环境安装地址 http://pan.baidu.com/s/1jGzNzyI 2 其他: 2.1 安装 2.1.1 安装JDK,JRE 成功安装之后,进行测试是否真的成功安装,点击[开始]----[运行]----输入 CMD,在命令提示符里面输入"Java -version"并按回车键,出现版本号则安装成功. 2.1.2 安装Adb 2.1.3 打开Eclipse 2.2 配置环境变量: 2.2.1 配置JAVA环境变量 (见下方2.2

android ListView中CheckBox错位的解决

貌似已经很晚了,但是还是想记下笔记,想让今天完满. 在ListView中加了checkBox,可是发现点击改变其选中状态的时候,发现其位置错乱.状态改变的并不是你选中的,百思不得其解.后面通过上网查资料,可是个说纷纭,但是我还是找到了解决办法. 在自定义的适配器中,对checkBox的设置如下: 记住两者的顺序,先对checkBox进行事件监听,再设置其状态.前提在布局中对checkBox的状态设为false. android ListView中CheckBox错位的解决,布布扣,bubuko.

Java AOP nested exception is java.lang.NoClassDefFoundError: org/aopalliance/aop/Advice || Error creating bean with name &#39;org.springframework.aop.aspectj.AspectJPointcutAdvisor#0&#39; 两个异常解决办法

贴出applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://ww

android.os.BadParcelableException: ClassNotFoundException when unmarshalling:解决办法

例如在用AlarmManager的时候 1 AlarmManager alarmMgr = (AlarmManager) mContext 2 .getSystemService(Context.ALARM_SERVICE); 3 Intent intent = new Intent(ALARM_ALERT); 4 // intent.setExtrasClassLoader(DBTask.class.getClassLoader()); 5 Bundle mBundle=new Bundle(

关于 java 上传,下载和导入报java.lang.IllegalStateException异常解决办法

java.lang.IllegalStateException异常解决办法 最近在使用response.sendRedirect()时出现如下错误:java.lang.IllegalStateException            org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:423) 经过分析.查看jdk文档终于找到解决的办法,在response.sendRedirect()方法后加

android sqlite3程序不存在的解决办法(转)

在android开发中,在使用命令行操作数据库sqlite时,有时候会遇到sqlite3 not found的问题.这是因为你的手机没有安装sqlite3程序.解决办法如下(两种办法结合起来解释的更清楚!!!): 方法1: sqlite3 not found的解决办法(转) 在Android开发方面,我是小白,起步没多久.最近用到了sqlite本地缓存数据,我希望像mysql一样通过命令行查看建立的表以及表中的数据,于是用adb shell进入,敲入sqlite3,提示 sqlite3: not