1. 程式人生 > >android遍歷所有子檢視

android遍歷所有子檢視

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View view = this.getWindow().getDecorView();
        // 遍歷你想要遍歷的的父檢視,並返回檢視集合
        List<View> viewList = getAllChildViews(view);
        for (int i = 0; i < viewList.size(); i++) {
            View v = viewList.get(i);
            if (v != null) {
                // 攔截監聽觸控事件
                v.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                break;
                            case MotionEvent.ACTION_MOVE:
                                break;
                            case MotionEvent.ACTION_UP:
                                break;
                        }
                        return false;
                    }
                });
            }
        }
    }

    /**
     * 獲取傳入指定檢視下的所有子檢視
     *
     * @param view
     * @return
     */
    private List<View> getAllChildViews(View view) {
        List<View> allChildViews = new ArrayList<>();
        if (view != null && view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewChild = vp.getChildAt(i);
                allChildViews.add(viewChild);
                // 遞迴
                allChildViews.addAll(getAllChildViews(viewChild));
            }
        }
        return allChildViews;
    }

}