Android - Create app with pure Java and no XML?

前端 未结 6 934
清酒与你
清酒与你 2020-12-08 14:38

I\'m wondering if it is possible to create an Android app with only Java. No XML, no other things.

In Eclipse, when I create a new Android Project, the Manifest xml-

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 15:22

    yes it's possible to make an app with java and no xml.
    here's a simple example.
    i use eclipse.
    first i made my own my class called MyView, which extends View.

    public class MyView extends View {
    
        Paint paint;
    
        public MyView(Context context) {
            super(context);
            setBackgroundColor(Color.BLACK);
            paint = new Paint();
            paint.setColor(Color.GREEN);
            paint.setTextSize(50);
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawCircle(50, 50, 50, paint);
            canvas.drawText("hello", 0, 150, paint);
            canvas.drawLine(0, 150, 100, 170, paint);
        }
    
    }
    

    in the activity, i create a MyView object called myView.
    i get rid of setContentView(R.layout.activity_main);
    then i type setContentView(myView);

    public class MainActivity extends Activity {
    
        MyView myView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    //      setContentView(R.layout.activity_main); // i delete this
            myView = new MyView(this);
            setContentView(myView);
        }
    }
    

    res\layout\activity_main.xml file can now be deleted.
    res\layout folder can now be deleted.

提交回复
热议问题