GhostView

2017-03-20  本文已影响0人  李怡锟

GhostView可以在不改变View的parent的情况下,在自己的Overlay里绘制另一个View。被绘制的View不会在它的Parent里绘制,因为View的visibility被设为INVISIBLE。GhostView使用被绘制的View的 render node去绘制。当GhostView为VISIBLE时,它所绘制的View为INVISIBLE;当GhostView为INVISIBLE时,它所绘制的View为VISIBLE。

public class GhostView extends View

构造方法:和被绘制的View相互持有,将被绘制的View的transition visibility设为INVISIBLE,触发View的Parent刷新。

绘制方法:使用View的updateDisplayListIfDirty获取RenderNode进行绘制

创建方法:addGhost(View , ViewGroup , Matrix) 与 addGhost(View , ViewGroup)

Example:

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView textView = (TextView) this.findViewById(R.id.textview);
    ColorDrawable colorDrawable = new ColorDrawable(Color.BLUE);
    colorDrawable.setAlpha(100);
    colorDrawable.setBounds(0, 0, 200, 200);
    textView.getOverlay().add(colorDrawable);

    final FrameLayout frameLayout = (FrameLayout) this.findViewById(R.id.frameLayout);
    frameLayout.setRight(frameLayout.getLeft() + 500);
    frameLayout.setBottom(frameLayout.getTop() + 200);
    MainActivity.this.addGhost(textView, frameLayout);

    this.findViewById(R.id.textview2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            textView.setText("Change To another");
        }
    });
}

private void addGhost(View view, ViewGroup viewGroup) {
    try {
        Class ghostViewClass = Class.forName("android.view.GhostView");
        Method addGhostMethod = ghostViewClass.getMethod("addGhost", View.class,
                ViewGroup.class, Matrix.class);
        View ghostView = (View) addGhostMethod.invoke(null, view, viewGroup, null);
        ghostView.setBackgroundColor(Color.YELLOW);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

效果:

device-2017-03-20-164414.png

点击CHANGE按钮,改变Button的Text,可以看到GhostView也随之更新:

将GhostView设为INVISIBLE,原来的View正常绘制:

device-2017-03-20-164430.png
上一篇下一篇

猜你喜欢

热点阅读