我想让视图在另一个视图前移动。我使用相对布局,以便z顺序如下工作。
activity_main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="300dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="200dp"
android:layout_height="300dp"
android:text="."
android:textSize="200dp" />
</RelativeLayout>
MainActivity.java:当用户触摸textView1时,textView2根据触摸事件的X移动。
public class MainActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView1 = (TextView) findViewById(R.id.textView1);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
textView1.setBackgroundColor(Color.GREEN);
textView1.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
textView2.setLeft((int) event.getX());
return true;
}
});
}
@Override
public void onClick(View arg0) {
}
}
但是textView2奇怪地消失在某个X坐标之外(好像它落在一个看不见的第三个视图后面),如下所示:
The beginning:
+-------------------------------+
| |
| +----+ |
| | | |
| | | |
| +----+ |
| |
+-------------------------------+
Moving to the right..
+-------------------------------+
| |
| +----+ |
| | | |
| | | |
| +----+ |
| |
+-------------------------------+
.. and starts to disappear at a certain X.
+-------------------------------+
| |
| +-- |
| | |
| | |
| +-- |
| |
+-------------------------------+
有什么问题?
答案 0 :(得分:1)
你的填充权是不是太重要了:
android:paddingRight="@dimen/activity_horizontal_margin"
您确定使用setLeft()
是个好主意吗?也许,最好通过LayoutParam?
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(event.getX(), 0, 0, 0);
textView2.setLayoutParams(params);