mLayout.addView()只能工作一次

时间:2016-05-15 19:54:47

标签: android

我最近开始为Android开发,并试图将多个视图添加到布局。它实际上适用于第一次触摸,但之后它什么也没做。 Log虽然继续工作并显示已检测到触摸并显示事件的位置。我有以下代码

public class MainActivity extends Activity {
private LinearLayout mLayout;
private Context con = this;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mLayout = (LinearLayout) findViewById(R.id.lLayout);
    mLayout.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:
                    mLayout.addView(createNewView(event.getX(), event.getY()));
                    Log.d("this ","View has been add." + event.getX()+ ", " + event.getY());
                    break;
            }
            return false;
        }
    });
}

private markerView createNewView(float x, float y) {
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    final markerView mView = new markerView(con, 150, x, y);
    mView.setLayoutParams(lparams);
    return mView;
}}

和     public class markerView extends View实现View.OnTouchListener {

private Paint paint = new Paint();
private int diameter;
private float X,Y;

public markerView(Context context, int dia, float dx, float dy) {
    super(context);
    diameter = dia;
    X = dx; Y = dy;
    paint.setColor(Color.GREEN);
    paint.setStyle(Style.STROKE);
    paint.setStrokeWidth((float) 4.0);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.drawCircle(X, Y, diameter, paint);
    canvas.restore();
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    return true;
}}

2 个答案:

答案 0 :(得分:1)

我刚刚发现视图已经创建但从未显示,因为第一个具有parentLayout的大小。所以我只是添加以下方法,它的工作原理。因为RelativeLayout需要更改位置,但这不是问题;) 这是代码:

         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <addMavenDescriptor>false</addMavenDescriptor>
                    <manifest>
                        <addClasspath>false</addClasspath>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

答案 1 :(得分:0)

尝试删除final

上的final markerView mView = new markerView(con, 150, x, y);标记