Android中ExpandableListView中含有Checkbox,Group長按事件無效,ChildItem長按事件有效

主頁面代碼,其中只有<span style="font-family: Arial, Helvetica, sans-serif;">R.id.rbTwo頁面有效</span>
public class MainActivity extends FragmentActivity {
	private Fragment[] mFragments;
	private RadioGroup bottomRg;
	private FragmentManager fragmentManager;
	private FragmentTransaction fragmentTransaction;
	private RadioButton rbOne, rbTwo, rbThree;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fullscreen);
		mFragments = new Fragment[3];  
        fragmentManager = getSupportFragmentManager();  
        mFragments[0] = fragmentManager.findFragmentById(R.id.fragment_first);  
        mFragments[1] = fragmentManager.findFragmentById(R.id.fragment_main);  
        mFragments[2] = fragmentManager .findFragmentById(R.id.fragment_third);  
        fragmentTransaction = fragmentManager.beginTransaction().hide(mFragments[0]).hide(mFragments[1]).hide(mFragments[2]);  
        fragmentTransaction.show(mFragments[0]).commit();  
        setFragmentIndicator();  
	}


	private void setFragmentIndicator() {
		// TODO Auto-generated method stub
		bottomRg = (RadioGroup) findViewById(R.id.bottomRg);  
        rbOne = (RadioButton) findViewById(R.id.rbOne);  
        rbTwo = (RadioButton) findViewById(R.id.rbTwo);  
        rbThree = (RadioButton) findViewById(R.id.rbThree);  
        bottomRg.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  
            @Override  
            public void onCheckedChanged(RadioGroup group, int checkedId) {  
                fragmentTransaction = fragmentManager.beginTransaction()  
                        .hide(mFragments[0]).hide(mFragments[1])  
                        .hide(mFragments[2]);  
                switch (checkedId) {  
                case R.id.rbOne:  
                    fragmentTransaction.show(mFragments[0]).commit();  
                    break;  
  
                case R.id.rbTwo:  
                    fragmentTransaction.show(mFragments[1]).commit();  
                    break;  
  
                case R.id.rbThree:  
                    fragmentTransaction.show(mFragments[2]).commit();  
                    break;  
  
                default:  
                    break;  
                }  
            }  
        });  
	}
<pre name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif;">R.id.rbTwo所對應的頁面</span>

public class SecondFragment extends Fragment {
	private String TAG=this.getClass().getSimpleName();
	ExpandableListView secondexpandableListView;
	private MenuPopupWindow menuPopupWindow;
	ArrayList<Group> groups;  
       EListAdapter adapter;  
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.secondfragment, container, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initView();
		initData();
	}

	
	
	private void initData() {
		// TODO Auto-generated method stub
		groups = new ArrayList<Group>();  
		getJSONObject(); 
		adapter = new EListAdapter(getActivity(), groups);  
		secondexpandableListView.setAdapter(adapter);  
		
	}

	private void getJSONObject() {
		// TODO Auto-generated method stub
		   String jsonStr = "{'CommunityUsersResult':[{'CommunityUsersList':[{'fullname':'a111','userid':11,'username':'a1'}"  
	                + ",{'fullname':'b222','userid':12,'username':'b2'}],'id':1,'title':'人事部'},{'CommunityUsersList':[{'fullname':"  
	                + "'c333','userid':13,'username':'c3'},{'fullname':'d444','userid':14,'username':'d4'},{'fullname':'e555','userid':"  
	                + "15,'username':'e5'}],'id':2,'title':'開發部'}]}";  
	  
	        try {  
	            JSONObject CommunityUsersResultObj = new JSONObject(jsonStr);  
	            JSONArray groupList = CommunityUsersResultObj.getJSONArray("CommunityUsersResult");  
	  
	            for (int i = 0; i < groupList.length(); i++) {  
	                JSONObject groupObj = (JSONObject) groupList.get(i);  
	                Group group = new Group(groupObj.getString("id"), groupObj.getString("title"));  
	                JSONArray childrenList = groupObj.getJSONArray("CommunityUsersList");  
	  
	                for (int j = 0; j < childrenList.length(); j++) {  
	                    JSONObject childObj = (JSONObject) childrenList.get(j);  
	                    Child child = new Child(childObj.getString("userid"), childObj.getString("fullname"),  
	                            childObj.getString("username"));  
	                    group.addChildrenItem(child);  
	                }  
	  
	                groups.add(group);  
	            }  
	        } catch (JSONException e) {  
	            Log.d("allenj", e.toString());  
	        }  
	}
	

	private void initView() {
		// TODO Auto-generated method stub
		secondexpandableListView=(ExpandableListView) getView().findViewById(R.id.secondexpandableListView);
		
		secondexpandableListView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				 longClickListIteam(view);  
				return false;
			}
	
		});
	}
	
	protected void longClickListIteam(View view) {
		// TODO Auto-generated method stub
		  final int groupPos = (Integer)view.getTag(R.id.getGroupId);      
          final int childPos = (Integer)view.getTag(R.id.getChildId);
          Log.i(TAG, "groupPos:"+groupPos+",childPos:"+childPos);
          if (childPos==-1) {
        	  Log.i(TAG,"操作group組件");  
		}else {
			menuPopupWindow=new MenuPopupWindow(getActivity(), itemsOnClick);
			 //顯示窗口
			menuPopupWindow.showAtLocation(getActivity().findViewById(R.id.mainLayout), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //設置l
			
		}
		
	}

	//爲彈出窗口實現監聽類
    OnClickListener  itemsOnClick = new OnClickListener(){
        public void onClick(View v) {
        	//menuPopupWindow.dismiss();
            switch (v.getId()) {
            case R.id.newbill_bt:
                break;
            case R.id.del_bt:               
                break;
            default:
                break;
            }
        }
         
    };


}
自定義EListAdapter 如下
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.example.lcc.R;
import com.example.lcc.vo.Child;
import com.example.lcc.vo.Group;

public class EListAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnChildClickListener {

	private Context context;
	private ArrayList<Group> groups;
	
	
	public EListAdapter(Context context,ArrayList<Group> groups) {
		// TODO Auto-generated constructor stub
		this.context=context;
		this.groups=groups;
	}
	
	@Override
	public int getGroupCount() {
		// TODO Auto-generated method stub
		return groups.size();
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		// TODO Auto-generated method stub
		return groups.get(groupPosition).getChildrenCount();
	}

	@Override
	public Object getGroup(int groupPosition) {
		// TODO Auto-generated method stub
		return groups.get(groupPosition);
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return groups.get(groupPosition).getChildItem(childPosition);
	}

	@Override
	public long getGroupId(int groupPosition) {
		// TODO Auto-generated method stub
		return groupPosition;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return childPosition;
	}

	@Override
	public boolean hasStableIds() {
		// TODO Auto-generated method stub
		return true;
	}

	/* (non-Javadoc)  
	 * @see android.widget.ExpandableListAdapter#getGroupView(int, boolean, android.view.View, android.view.ViewGroup)  
	 * 設定Group資料
	 */
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		Group group=(Group) getGroup(groupPosition);
		if (convertView==null) {
			LayoutInflater infalInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView=infalInflater.inflate(R.layout.group_item, null);
		}
		convertView.setTag(R.id.getGroupId, groupPosition);
		convertView.setTag(R.id.getChildId,-1);
		TextView tv=(TextView) convertView.findViewById(R.id.tvGroup);
		tv.setText(group.getTitle());
		// 重新產生 CheckBox 時,將存起來的 isChecked 狀態重新設定  
		CheckBox checkBox=(CheckBox) convertView.findViewById(R.id.chbGroup);
		checkBox.setChecked(group.getChecked());  
		// 點擊 CheckBox 時,將狀態存起來  
        checkBox.setOnClickListener(new Group_CheckBox_Click(groupPosition));  
		return convertView;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		 Child child = groups.get(groupPosition).getChildItem(childPosition);  
		   
	        if (convertView == null) {  
	            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
	            convertView = inflater.inflate(R.layout.children, null);  
	        }  
	        
	        convertView.setTag(R.id.getGroupId, groupPosition);
	        convertView.setTag(R.id.getChildId,childPosition);
	        TextView tv = (TextView) convertView.findViewById(R.id.tvChild);  
	        tv.setText(child.getFullname());  
	   
	        // 重新產生 CheckBox 時,將存起來的 isChecked 狀態重新設定  
	        CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chbChild);  
	        checkBox.setChecked(child.getChecked());  
	   
	        // 點擊 CheckBox 時,將狀態存起來  
	        checkBox.setOnClickListener(new Child_CheckBox_Click(groupPosition, childPosition));  
	   
	        return convertView;  
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		// TODO Auto-generated method stub
		 handleClick(childPosition, groupPosition);  
	     return true;  
	}
	
	 /** 勾選 Group CheckBox 時,存 Group CheckBox 的狀態,以及改變 Child CheckBox 的狀態 */  
    class Group_CheckBox_Click implements OnClickListener {  
        private int groupPosition;  
   
        Group_CheckBox_Click(int groupPosition) {  
            this.groupPosition = groupPosition;  
        }  
   
        public void onClick(View v) {  
            groups.get(groupPosition).toggle();  
   
            // 將 Children 的 isChecked 全面設成跟 Group 一樣  
            int childrenCount = groups.get(groupPosition).getChildrenCount();  
            boolean groupIsChecked = groups.get(groupPosition).getChecked();  
            for (int i = 0; i < childrenCount; i++)  
                groups.get(groupPosition).getChildItem(i).setChecked(groupIsChecked);  
   
            // 注意,一定要通知 ExpandableListView 資料已經改變,ExpandableListView 會重新產生畫面  
            notifyDataSetChanged();  
        }  
    }  
    
    /** 勾選 Child CheckBox 時,存 Child CheckBox 的狀態 */  
    class Child_CheckBox_Click implements OnClickListener {  
        private int groupPosition;  
        private int childPosition;  
   
        Child_CheckBox_Click(int groupPosition, int childPosition) {  
            this.groupPosition = groupPosition;  
            this.childPosition = childPosition;  
        }  
   
        public void onClick(View v) {  
            handleClick(childPosition, groupPosition);  
        }  
    }  
    
    public void handleClick(int childPosition, int groupPosition) {  
        groups.get(groupPosition).getChildItem(childPosition).toggle();  
          
        // 檢查 Child CheckBox 是否有全部勾選,以控制 Group CheckBox  
        int childrenCount = groups.get(groupPosition).getChildrenCount();  
        boolean childrenAllIsChecked = true;  
        for (int i = 0; i < childrenCount; i++) {  
            if (!groups.get(groupPosition).getChildItem(i).getChecked())  
                childrenAllIsChecked = false;  
        }  
  
        groups.get(groupPosition).setChecked(childrenAllIsChecked);  
  
        // 注意,一定要通知 ExpandableListView 資料已經改變,ExpandableListView 會重新產生畫面  
        notifyDataSetChanged();  
    }  
    
}
確保唯一性
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="getGroupId" type="id"/>
    <item name="getChildId" type="id"/>
    
</resources>
R.id.rbTwo對應的頁面
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
 

    <ExpandableListView
        android:id="@+id/secondexpandableListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ExpandableListView>

</LinearLayout>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章