如何将按钮添加到 android java 代码中?它是主要活动java代码:
package com.example.pafima_trial;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SingleTouchEventView(this, null));
// setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
它是 SingleTouchEventView.java
public class SingleTouchEventView extends View {
private Paint paint = new Paint();
private Path path = new Path();
boolean touched = false;
float x =0;
float y =0;
float [] inputx = new float[200];
float [] inputy = new float[200];
String [] direction = new String [200];
int count =0;
int dcount =0;
public SingleTouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
touched=true;
inputx[count]=eventX;
inputy[count]=eventY;
System.out.println("x is: "+ inputx[count]);
System.out.println("y is: "+inputy[count]);
if(count>=2 && count%2 != 1){
if(inputx[count-2]-inputx[count]<=-15){
if(inputy[count-2]-inputy[count]<=-15){
direction[dcount]="right down";
dcount++;
}
if(inputy[count-2]-inputy[count]>15){
direction[dcount]="right up";
dcount++;
}
if(-14<=inputy[count-2]-inputy[count] && inputy[count-2]-inputy[count]<=15 ){
direction[dcount]="right";
dcount++;
}
}
if(inputx[count-2]-inputx[count]>15){
if(inputy[count-2]-inputy[count]>=15){
direction[dcount]="left up";
dcount++;
}
if(inputy[count-2]-inputy[count]<-15){
direction[dcount]="left down";
dcount++;
}
if(15>inputy[count-2]-inputy[count] && inputy[count-2]-inputy[count]>=-15 ){
direction[dcount]="left";
dcount++;
}
}
if (inputx[count-2]-inputx[count]<=15 && inputx[count-2]-inputx[count]>-15){
if(inputy[count-2]-inputy[count]<-15){
direction[dcount]="down";
dcount++;
}
if(inputy[count-2]-inputy[count]>=15){
direction[dcount]="up";
dcount++;
}
}
}
count++;
break;
case MotionEvent.ACTION_UP:
System.out.println("count is "+count);
break;
default:
return false;
}
int a =0;
while(a<dcount){
System.out.println("direction["+a+"] is: "+ direction[a]);
a++;
}
// Schedules a repaint.
invalidate();
return true;
}
}
我无法在主活动 java 代码中添加按钮,我无法将活动主 xml 文件设置为内容视图。我也可以在java代码中提供指向xml文件的链接吗?