標籤:listview 焦點 item 控制項
在開發中,listview可以說是我們使用最頻繁的控制項之一了,但是關於listview的各種問題也是很多。當我們使用自訂布局的Listview的時候,如果在item的布局檔案裡面存在Button或者是CheckBox等控制項以及其子類控制項的時候,經常會碰到各種控制項的點擊事件衝突的情況,那麼我們如何來處理Listview中這種控制項之間焦點衝突的情況呢?
我們以item存在一個Button控制項為例
首先,加入我們不設定任何關於焦點的屬性,比如focus等,代碼如下
@Overridepublic View getView(int position, View convertView, ViewGroup parent) {convertView = inflater.inflate(R.layout.item, null);Button btnButton = (Button) convertView.findViewById(R.id.btn);btnButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(context, "點擊了按鈕", 0).show();}});return convertView;}
設定listview的OnitemClickListener事件
@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {Toast.makeText(context, "點擊了Item", 0).show();}
那麼在上面這種情況下,我們可以觸發Button的點擊事件,但是item的點擊事件並不會被觸發,也就是說,Button控制項搶奪了item的焦時間點事件,使得item不能觸發相應的點擊事件,那麼,如果我們既想觸發Button的點擊事件,又想觸發item的點擊事件,我們應該怎麼做呢?
這裡有三種解決方案
1.將ListView中的Item布局中的子控制項focusable屬性設定為false
2.在getView方法中設定button.setFocusable(false)
3.設定item的根布局的屬性android:descendantFocusability="blocksDescendant"
我們可以發現,其實這三種方法都是為了讓Button等控制項不能擷取焦點,從而使得item可以響應點擊事件。
第三種方法使用起來相對方便,因為它是將item布局中的其他所有控制項都設定為不能擷取焦點。
android:descendantFocusability屬性共有三個取值,分別為
beforeDescendants:viewgroup會優先其子類控制項而擷取到焦點
afterDescendants:viewgroup 只有當其子類控制項不需要擷取焦點時才擷取焦點
blocksDescendants:viewgroup 會覆蓋子類控制項而直接獲得焦點