实现一 往根布局里加,比较麻烦,好像还要考虑外层布局
public class MainActivityC extends AppCompatActivity {
String TAG="-------------------";
RelativeLayout inflate;
RelativeLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (RelativeLayout)findViewById(R.id.ro);
inflate = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.a1, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e("-------"," "+event.getAction()+" x "+event.getX()+" y "+event.getY());
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
ll.removeView(inflate);
inflate.setX(event.getX());
inflate.setY(event.getY());
inflate.setZ(100);
ll.addView(inflate);
break;
case MotionEvent.ACTION_MOVE:
inflate.setX(event.getX());
inflate.setY(event.getY());
break;
case MotionEvent.ACTION_UP:
ll.removeView(inflate);
break;
}
return super.onTouchEvent(event);
}
}
实现二 比较简单,往Window上加一层位置也比较正确,其他情况待验
public class MainActivityC extends AppCompatActivity {
RelativeLayout inflate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Window window = getWindow();
inflate = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.a1, null);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
inflate.setLayoutParams(layoutParams);
window.addContentView(inflate,inflate.getLayoutParams());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e("-------"," "+event.getAction()+" x "+event.getX()+" y "+event.getY());
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
inflate.setX(event.getX());
inflate.setY(event.getY());
inflate.setZ(100);
inflate.setVisibility(View.VISIBLE);
break;
case MotionEvent.ACTION_MOVE:
inflate.setX(event.getX());
inflate.setY(event.getY());
break;
case MotionEvent.ACTION_UP:
inflate.setVisibility(View.GONE);
break;
}
return super.onTouchEvent(event);
}
}