How to change ContentView when a button is clicked?

1000 views Asked by At

Hey guys, I need help with changing a ContentView in the MainActivity (without changing the Activity). I want to display "Special Thanks". In there are names of users who helped me localizing and testing the app. For that, I am using a button with

android:onClick="onSpcThxButtonClick"

The xml I want to display is called "spcthx.xml"

I need you to complete the following code:

public void onSpcThxButtonClick (View view)
{
        // insert ContentView switch here
}

Hope you are able to help me.

Thanks in advance!

2

There are 2 answers

2
Sebastian Olivares On

Try this.

<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".Settings" >

<!-- Settings  -->
<LinearLayout
    android:id="@+id/settings_form"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    >

</LinearLayout>

<!-- Special Thanks -->
<LinearLayout 
    android:id="@+id/special_thanks_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:visibility="gone"
    >


</LinearLayout>

Then on your Activity just reference them

private View            settingsForm;
private View            specialThanksForm;

settingsForm      = findViewById(R.id.settings_form);
specialThanksForm = findViewById(R.id.special_thanks_form);

Then change the visibility for the Views on your button clickListener

settingsForm.setVisibility(View.GONE);
specialThanksForm.setVisibility(View.VISIBLE);
4
Aaron Hernandez On

You can't use setcontentview easily on just calling a setcontentview function. You can use Framelayout to remove all views and inflate new layout to change/switch different views. I hope this will help.