開發(fā)過程中有個地方使用了ViewStub,但是發(fā)現(xiàn)ViewStub調(diào)用setTranslationX之后并沒有任何反應(yīng),經(jīng)過一番實驗,發(fā)現(xiàn)使用inflate獲取了View之后,再對View使用setTranslationX才會有效果
public class ViewStubTestActivity extends Activity {
ViewStub sb1;
ViewStub sb2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_viewstub);
sb1 = (ViewStub) findViewById(R.id.stub_1);
sb2 = (ViewStub) findViewById(R.id.stub_2);
// sb1.setVisibility(View.VISIBLE); // 或者使用sb1.inflate()
// sb1.setTranslationX(100); // 然后這個并沒有效果
sb1.inflate().setTranslationX(100); // 這個才有效
}
}
簡單讀了一下源碼,發(fā)現(xiàn)ViewStub在實例化具體內(nèi)容的時候,把自己給移除了,同時將具體內(nèi)容作為一個引用存了下來。而不是自身轉(zhuǎn)換為目標(biāo),也不是自己將目標(biāo)作為自身的子view。
所以我們應(yīng)該去用這個mInflatedViewRef所指代的View
而不是用ViewStub本身。
貼一段源碼。
/**
* Inflates the layout resource identified by {@link #getLayoutResource()}
* and replaces this StubbedView in its parent by the inflated layout resource.
*
* @return The inflated layout resource.
*
*/
public View inflate() {
final ViewParent viewParent = getParent();
if (viewParent != null && viewParent instanceof ViewGroup) {
if (mLayoutResource != 0) {
final ViewGroup parent = (ViewGroup) viewParent;
final LayoutInflater factory;
if (mInflater != null) {
factory = mInflater;
} else {
factory = LayoutInflater.from(mContext);
}
final View view = factory.inflate(mLayoutResource, parent,
false);
if (mInflatedId != NO_ID) {
view.setId(mInflatedId);
}
final int index = parent.indexOfChild(this);
parent.removeViewInLayout(this);
final ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams != null) {
parent.addView(view, index, layoutParams);
} else {
parent.addView(view, index);
}
mInflatedViewRef = new WeakReference<View>(view);
if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
}
return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
}
以上。