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.
2 Answers
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.

- 1,711
- 3
- 13
- 23
-
So every time you add a new activity you have to also add it into the `Androidmanifest.xml`? – lets0code Nov 20 '18 at 17:25
-
Yes. You have to do that. – Ishaan Javali Nov 20 '18 at 17:25
-
If this answer helped you moegizzle, please mark it as accepted so that those who are facing similar problems can refer to this answer to get help as well. – Ishaan Javali Nov 20 '18 at 17:28
-
I am happy that I was able to help moegizzle! – Ishaan Javali Nov 20 '18 at 17:34
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

- 81
- 2
- 9