Kaivalya Vyas
Kaivalya Vyas

Reputation: 21

Activity_main.xml is not updated in Android studio 1.5

I am editing UI in Content_main.xml but when I try to access any button in mainactivity.java it throws null pointer exception because all entries are there in content file not in activity file so what should I do to access my buttons which were added in Content file.

Upvotes: 2

Views: 259

Answers (2)

pony
pony

Reputation: 1381

Now in Android Studio ,when you start a new project ,AS generate two .xml layout file for you .

  1. The activity_main.xml file help you to better control your MainActivity ,for there actually have AppBarLayout and FloatingActionButton , it save you more time to get started with material design rule .
  2. The content_main.xml file only cares your main content ,what your main layout views go here.

This two files connected by include tag , and you can use them in the Activity java file as what you like . Such as findViewById() method .

Upvotes: 0

Knut Valen
Knut Valen

Reputation: 256

In your MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.myButton);
}

And in your activity_main.xml:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.myapplication.MainActivity">

<include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

And in your content_main.xml:

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.myapplication.MainActivity"
tools:showIn="@layout/activity_main">

<Button
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:id="@+id/myButton"/>

</RelativeLayout>

Upvotes: 1

Related Questions