How to change the content view with a button using setcontent

Joshua Unrau picture Joshua Unrau · Jul 25, 2014 · Viewed 15.2k times · Source

I have seen many tutorials on how to change the screen for android yet i am not able to understand/make work all of them can some one help me with my project. i have four xml files all of which have three buttons but only two will be used to set the page. I can get the app to load any one of the other pages (but then cannot establish buttons)(the important bit). Any help is appreciated.

package com.store.shrek2;


import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
int activityloaded = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Button button1 = (Button) this.findViewById(R.id.button1);
    Button button2 = (Button) this.findViewById(R.id.button2);
    Button button3 = (Button) this.findViewById(R.id.button3);
    Button button4 = (Button) this.findViewById(R.id.button4);
    Button button5 = (Button) this.findViewById(R.id.button5);
    Button button6 = (Button) this.findViewById(R.id.button6);
    if(activityloaded == 1){
    button1.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        }});
    button2.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            activityloaded = 2;
        }});
    button3.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            activityloaded = 4;
            setContentView(R.layout.activity4);
        }});
    }
    if(activityloaded == 2){
    setContentView(R.layout.activity2);
    button4.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            setContentView(R.layout.activity3);
        }});
    }
    }
 }



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.store.shrek2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity2"></activity>
    <activity android:name=".activity3"></activity>
    <activity android:name=".activity4"></activity>
</application>

</manifest>

Answer

Eenvincible picture Eenvincible · Jul 25, 2014

Please follow these instructions to get an idea on how to solve your problem.

  • First, create one activity - call it MainActivity
  • Secondly, create your fragments - depending on how many they are:
  • Thirdly, create your respective xml files for those fragments.
  • Fourthly, assuming all the fragments you have contain totally different types of views - if they don't, you could reuse your fragments and reduce the number of them.
  • I take it that your buttons are in the main view - from where you can touch them to switch to new layouts and such.

Since you will be using your main activity to manage your fragments,

  • Implement a click listener and attach it to your buttons.
  • Secondly, switch your button's id (use a switch statement) and when a given button is clicked,
  • Create a new instance of your respective fragment and set it or in other words, load it to view (add). You can optionally add it to the backstack so that a user can easily navigate back to it using the back button.
  • When someone clicks another button, say button2, do the same thing as when they clicked button1 except load the correct fragment.
  • The point of using fragments is to be able to reuse them. That also helps you avoid doing too much work in your activities since fragments can do all they need on their own.

Example Code : MainActivity.java

public class MainActivity extends Activity implements View.OnClickListener
{
    private Button mLoadFragmentOne;
    private Button mLoadFragmentTwo;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);

       mLoadFragmentOne = (Button)findViewById(R.id.buttonOne);
       mLoadFragmentTwo = (Button)findViewById(R.id.buttonTwo);

       mLoadFragmentOne.setOnClickListener(this);
       mLoadFragmentTwo.setOnClickListener(this);

    }

    @Override
    public void onClick(View view)
    {
        switch(view.getId())
        {
           case R.id.buttonOne:
               FragmentOne fragmentOne = new FragmentOne();

               loadFragment(fragmentOne, "fragmentOne");

               break;
           case R.id.buttonTwo:
               FragmentTwo fragmentTwo = new FragmentTwo();

               loatFragment(fragmentTwo, "fragmentTwo");

               break;
           default:
               break;
        }
    }

    /**
    * This fragment container will be part of the main view.
    */
    public void loadFragment(Fragment frag, String tag)
    {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        Fragment fragment = getFragmentManager().findFragmentById(R.id.fragmentContainer);
        if(fragment == null)
        {
           ft.add(R.id.fragmentContainer, frag, tag);
        } else 
        {
           ft.replace(R.id.fragmentContainer, frag, tag);
        }
       ft.addToBackStack(null);

       ft.commit();
    }
}

FragmentOne.java

public class FragmentOne extends Fragment
{
   private final String TAG = "com.example.app.FragmentOne";

   private Activity mActivity;

   public void onAttach(Activity act)
   {
     super.onAttach(act);

     this.mActivity = act;
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
   {
      View view = inflater.inflate(R.layout.fragment_one, container, false);

      //do whatever you want here - like adding a listview or anything

      return view;
   }
}

FragmentTwo.java

public class FragmentTwo extends Fragment
{
   private final String TAG = "com.example.app.FragmentTwo";

   private Activity mActivity;

   @Override
   public void onAttach(Activity act)
   {
      super.onAttach(act);

      this.mActivity = act;
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
   {
     View view = inflator.inflate(R.layout.fragment_two, container, false);

     //do whatever you want here - like set text to display in your fragment

     return view;
   }
}

Now, you can simply use this code sample to get your job done.

The point here is to create a container - an example would be a frame layout in your main view, give it an id and just remember that this is where your fragments will be loaded.

You will have to add other stuff so that a user can easily navigate back and forth between views.

Finally, remember to create the two fragment xml files - they can contain whatever you want your users to see - like images, texts and lists or grids. It is your own choice.

That is all I could spare time for and I hope it helps you.

If you follow these instructions step by step, you should be able to get your issue solved. Good luck.