1. 程式人生 > >安卓Android控制元件ListView巢狀EditText控制元件

安卓Android控制元件ListView巢狀EditText控制元件

實現效果:


效果就是這樣,我們要實現這樣的效果,其實思路就是:

1、我們要記錄下按鈕的狀態,同時儲存文字框。

2、主要是在BaseAdapter中進行監聽。

class MyAdapter extends BaseAdapter{
		private Map<Integer,Integer> mapToggle;		//用於儲存Toggle的狀態
		private Map<Integer,String> mapReason;		//用於儲存文字框的內容
		public MyAdapter(){
			mapToggle = new HashMap<Integer,Integer>();
			mapReason = new HashMap<Integer,String>();
		}
		@Override
		public int getCount() {
			return 30;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
				convertView = LayoutInflater.from(_this).inflate(R.layout.activity_price_item, null);
				TextView tv_title = (TextView) convertView.findViewById(R.id.price_item_title);
				TextView tv_price = (TextView) convertView.findViewById(R.id.price_item_price);
				final EditText et_text = (EditText) convertView.findViewById(R.id.price_item_reason);
				ToggleButton toggleButton = (ToggleButton) convertView.findViewById(R.id.price_item_toggle);
				final LinearLayout linear= (LinearLayout) convertView.findViewById(R.id.price_relative);
				tv_title.setText("測試用例" + position);
				linear.setTag(position);
				et_text.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					
				}
				
				@Override
				public void afterTextChanged(Editable s) {//記錄文字框的內容
					int index = (Integer) linear.getTag();
					mapReason.put(index, s.toString());
				}
			});
		toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){
	            @Override
	            public void onCheckedChanged(CompoundButton buttonView,
	                    boolean isChecked) {
	                if(isChecked){
	                	int index = (Integer) linear.getTag();
	                	mapToggle.put(index, 0);
	                    linear.setVisibility(View.GONE);
	                }else{
	                	int index = (Integer) linear.getTag();
	                	mapToggle.put(index, 1);
	                    linear.setVisibility(View.VISIBLE);
	                }
	            }
	        });
			if(mapToggle != null){//重新恢復狀態
				int index = (Integer) linear.getTag();
				if(!mapToggle.keySet().isEmpty() && mapToggle.containsKey(index) && mapToggle.get(index) == 1){
					if(toggleButton.isChecked())
					toggleButton.setChecked(false);
				}else{
					toggleButton.setChecked(true);
				}
				if(!mapReason.keySet().isEmpty())
				et_text.setText(mapReason.get(index));
			}
			return convertView;
		}
	}