1

I am completely new to Android Studio and I was wondering when I create a new class, it doesn't contain the method public void onCreate. For example in my main_activity you have the super.onCreate(savedInstanceState) that would let you connect to your layout and then do things with fields or buttons. My question is how can I do the same when I create a new class. Do I just copy the public void onCreate into the new class and go about it that way. Or do I extend from main_activity. Really confused and trying to understand this.

Lekr0
  • 653
  • 1
  • 8
  • 17
lets0code
  • 153
  • 3
  • 17

2 Answers2

2

You can, but it will be complicated.

Simplest Way: What you can do is right click on the java folder, located on the left side in Android Studio. Then, go to "New" on the top. Look downwards and you will see "Activity". Hover on that and it will give you some different types of activities that you can create. By clicking on one of them, it automatically adds that activity to your AndroidManifest and it also creates the Java class, and XML file for the activity.

Longer Way: As you mentioned, you can copy and paste the onCreate method into the class. You would also have to add extends AppCompatActivity. Then, you will have to add the class to AndroidManifest by doing

   <activity
        android:name=".ActivityName"
        android:label="My Activity"
        android:theme="@style/MyAppTheme" />

Next, you will have to create an XML file. To the top of your file, you should add:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    **tools:context=".ActivityName"**>

Finally, you will have to go to your Java class and add the following in onCreate:

 super.onCreate(savedInstanceState);
 setContentView(R.layout.mylayoutfile);

These are two ways that you can create an activity.

Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
2

Have a look at the resource link : Create New Activity

This will create java class and the xml interface at the same time and it will add necessary lines to manifest.xml too