2014-09-23 36 views
3

我想要實現縮放維度值,例如一個自定義LayoutInflater時, 使用:鉤LayoutInflater和變化值充氣視圖

int scale = 2; 
MyInflater.inflate(R.id.testview, null, parent, scale); 

將膨脹一個xml與所有維度值加倍。

即,像這樣的XML:

<View android:layout_width="10dp" android:layout_height="10dp" /> 

將膨脹到該寬度和高度20dp的圖。

LayoutInflater.Factory無法解決我的問題。

有沒有一種方法可以實現這個目標?

+0

- 爲什麼不? – CommonsWare 2014-09-23 14:40:10

+0

@CommonsWare如果使用'LayoutInflater.Factory',我必須自己創建每個視圖,因爲沒有鏈接超級調用;並且LayoutParams生成不在'createViewFromTag()'中,Factory的'onCreateView()'被調用,所以在Factory的'onCreateView()'中,修改LayoutParams是不可能的。 – bladefury 2014-09-24 02:37:04

+0

我不太明白這個問題,你想膨脹時從xml的視圖縮放? – 2014-09-27 08:05:23

回答

5

也許你可以使用此代碼迴路所有孩子的充氣佈局和設置的LayoutParams乘以寬度和高度:「LayoutInflater.Factory解決不了我的問題」

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my); 

    MyInflater inflater = new MyInflater(LayoutInflater.from(this), this); 
    ViewGroup viewGroup = (ViewGroup) findViewById(R.id.my_layout); 
    inflater.inflate(R.layout.test_view, viewGroup, true, 2); 
} 

private class MyInflater extends LayoutInflater { 

    private int mScale; 

    protected MyInflater(LayoutInflater original, Context newContext) { 
     super(original, newContext); 
    } 

    @Override 
    public LayoutInflater cloneInContext(Context newContext) { 
     return null; 
    } 

    public View inflate(int resource, ViewGroup root, boolean attachToRoot, int scale) { 
     mScale = scale; 
     // This will return the parent of the inflated resource (if it has one) 
     View viewRoot = super.inflate(resource, root, attachToRoot); 

     if (viewRoot instanceof ViewGroup) { 
      loopViewGroup((ViewGroup) viewRoot, viewRoot == root); 
     } else { 
      doubleDimensions(viewRoot); 
     } 
     return viewRoot; 
    } 

    private void doubleDimensions(View view) { 
     ViewGroup.LayoutParams params = view.getLayoutParams(); 
     Log.d(TAG, "Before => "+params.width+" : "+params.height); 
     params.width = params.width * mScale; 
     params.height = params.height * mScale; 
     Log.d(TAG, "After => "+params.width+" : "+params.height); 
     view.setLayoutParams(params); 
    } 

    private void loopViewGroup(ViewGroup group, boolean isRoot) { 
     // If viewRoot == root, skip setting ViewGroup params 
     if (!isRoot) doubleDimensions(group); 

     // Loop the ViewGroup children 
     for (int i=0; i<group.getChildCount(); i++) { 
      View child = group.getChildAt(i); 
      // If a child is another ViewGroup, loop it too 
      if (child instanceof ViewGroup) { 
       loopViewGroup((ViewGroup) child, false); 
      } else { 
       doubleDimensions(child); 
      } 
     } 
    } 
} 
+0

這可以解決問題,但可能會有性能問題,在dp中縮放所有大小?我想*所有*尺寸縮放,所以我想在膨脹時修改xml attrs。 – bladefury 2014-09-28 02:25:19

+0

這種方法可以作爲備份計劃。 upvoted,謝謝! – bladefury 2014-09-28 02:29:29