如何在应用程序中获取所有TextViews值?

时间:2015-09-12 11:00:53

标签: android string textview

我试图找出是否有可能(以编程方式)获取应用程序中的所有TextViews值并将它们保存在ArrayList中?

ArrayList <TextView> textViews=new ArrayList<>();    
ViewTreeObserver vto = getWindow().getDecorView().getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        getAllText((ViewGroup)getWindow().getDecorView());
    }
});
void getAllText(ViewGroup viewGroup){


if (viewGroup == null) return;
for (int i=0; i<viewGroup.getChildCount(); i++)
{
    View view = viewGroup.getChildAt(i);
    if (view instanceof ViewGroup) getAllText((ViewGroup) view);
    if (view instanceof TextView){
        if(!(textViews.contains(view)))textViews.add((TextView) view);
    }
}

1 个答案:

答案 0 :(得分:0)

使用类似的东西:

private ArrayList<TextView> mTextViews;

@Override
onCreate(Bundle savedState) {
    setContentView(R.layout.activity);

    ViewGroup root = findViewById(R.id.root);

    mTextViews = new ArrayList<>();

    findTextViews(root);
}

private findTextView(ViewGroup root) {
    for (int i = 0; i < root.getChildCount(); i++) {
        View child = root.getChildAt(i);

        if (child instanceof TextView) {
             mTextViews.add(child);
        } else if (child instanceof ViewGroup) {
             findTextView((ViewGroup) child);
        }
    }
}