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 = 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;
    }

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