[java] android: how to change layout on button click?

I have to following code for selecting layout on button click.

View.OnClickListener handler = new View.OnClickListener(){
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.DownloadView: 
                // doStuff
                setContentView(R.layout.main);
                break;
            case R.id.AppView: 
                // doStuff
                setContentView(R.layout.app);
                break;
        }
    }
};

findViewById(R.id.DownloadView).setOnClickListener(handler);
findViewById(R.id.AppView).setOnClickListener(handler);

When I click the "AppView" button, the layout changes, but when I click the "DownloadView "button, nothing happens.

This link says that I have to start a new activity.

But I don't know how to use the code there of intent to start new activity, will a new file be added?

EDIT: I have my code on the new activity:

package com.example.engagiasync;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class AppView extends Activity implements OnClickListener{


    @Override
    public void onCreate(Bundle savedInstanceState){

        setContentView(R.layout.app);

        TextView tv = (TextView) this.findViewById(R.id.thetext);
        tv.setText("App View yo!?\n");
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

but it does not work, it force closes, the logcat says:enter image description here

This question is related to java android android-intent android-activity

The answer is


You wanted to change the layout at runtime on button click. But that is not possible and as it has been rightly stated above, you need to restart the activity. You will come across a similar problem when u plan on changing the theme based on user's selection but it will not reflect in runtime. You will have to restart the activity.


I would add an android:onClick to the layout and then change the layout in the activity.

So in the layout

<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>

Then in the activity add the following:

public void changelayout(View view){
    setContentView(R.layout.second_layout);
}

It is very simple, just do this:

t4.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            launchQuiz2();          // TODO Auto-generated method stub

        }

        private void launchQuiz2() {
            Intent i = new Intent(MainActivity.this, Quiz2.class);
            startActivity(i);
            // TODO Auto-generated method stub

        }

    });

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

I think what you're trying to do should be done with multiple Activities. If you're learning Android, understanding Activities is something you're going to have to tackle. Trying to write a whole app with just one Activity will end up being a lot more difficult. Read this article to get yourself started, then you should end up with something more like this:

View.OnClickListener handler = new View.OnClickListener(){
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.DownloadView: 
                // doStuff
                startActivity(new Intent(ThisActivity.this, DownloadActivity.class));
                break;
            case R.id.AppView: 
                // doStuff
                startActivity(new Intent(ThisActivity.this, AppActivity.class));
                break;
        }
    }
};

findViewById(R.id.DownloadView).setOnClickListener(handler);
findViewById(R.id.AppView).setOnClickListener(handler);

First I would suggest putting a Log in each case of your switch to be sure that your code is being called.

Then I would check that the layouts are actually different.


I know I'm coming to this late, but what the heck.

I've got almost the exact same code as Kris, using just one Activity but with 2 different layouts/views, and I want to switch between the layouts at will.

As a test, I added 2 menu options, each one switches the view:

public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.item1:
                setContentView(R.layout.main);
                return true;
            case R.id.item2:
                setContentView(R.layout.alternate);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

Note, I've got one Activity class. This works perfectly. So I have no idea why people are suggesting using different Activities / Intents. Maybe someone can explain why my code works and Kris's didn't.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-intent

Kotlin Android start new Activity Open Facebook Page in Facebook App (if installed) on Android Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23 Not an enclosing class error Android Studio Parcelable encountered IOException writing serializable object getactivity() Sending intent to BroadcastReceiver from adb How to pass ArrayList<CustomeObject> from one activity to another? Android Intent Cannot resolve constructor Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT Android - java.lang.SecurityException: Permission Denial: starting Intent

Examples related to android-activity

Kotlin Android start new Activity The activity must be exported or contain an intent-filter How to define dimens.xml for every different screen size in android? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Not an enclosing class error Android Studio java.lang.IllegalStateException: Fragment not attached to Activity Soft keyboard open and close listener in an activity in Android android.app.Application cannot be cast to android.app.Activity Android Shared preferences for creating one time activity (example) Android ListView with onClick items