简体   繁体   中英

How to increment a TextView value in a different activity with a button from the Main Activity?

Ok so I've tried asking this question before but I didn't quite get the right answer, so I'm going to be a lot more specific this time.

I have an app (Game that plays itself) , where you're a diety and can create followers with the click of a button. After clicking the Create Follower button, I want it to store the number of clicks to a variable called followerCount .

Here's the MainActivity.class:

    package com.couchmango.godslife;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import java.util.*;
import android.preference.*;

public class MainActivity extends Activity implements OnClickListener
    {
        //Declare Constant Variables
        private Button createFollowerButton;
        private int followerLimit;
        private boolean reachedFollowerLimit;
        public static int followerCount;


        //Called when activity opens
        @Override
        protected void onCreate(Bundle savedInstanceState)
            {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            //Create Button
            createFollowerButton = (Button)findViewById(R.id.createFollowerButton);
            createFollowerButton.setOnClickListener(this);

            };//End onCreate

        @Override
        public void onRestoreInstanceState(Bundle savedInstanceState)
            {
            super.onRestoreInstanceState(savedInstanceState);
            // Restore UI state from the savedInstanceState.
            // This bundle has also been passed to onCreate.

            }


        @Override
        public void onClick(View v)
            {
            switch(v.getId()){

                    //Milestones Button Pressed
                    //Goes to Milestones activity
                    case R.id.milestones:Intent intent = new Intent(MainActivity.this, milestones.class);
                    MainActivity.this.startActivity(intent);
                    break;

                    //God Stats Button Pressed
                    //Goes to God Stats activity
                    case R.id.godStats:intent = new Intent(MainActivity.this, godStats.class);
                    MainActivity.this.startActivity(intent);
                    break;

                    //Influence Button Pressed
                    //Goes to Influence activity
                    case R.id.influence:intent = new Intent(MainActivity.this, influence.class);
                    MainActivity.this.startActivity(intent);
                    break;

                    //Followers Button Pressed
                    //Goes to Followers activity
                    case R.id.followers:intent = new Intent(MainActivity.this, followers.class);
                    intent = new Intent(MainActivity.this, followers.class);
                    intent.putExtra("FollowerCount", followerCount);
                    MainActivity.this.startActivity(intent);

                    break;

                    //Create Follower Button Pressed
                    //Increases followerCount & adds to followerLimit
                    //if followerLimit is not reached
                    case R.id.createFollowerButton: 

                        if(reachedFollowerLimit == false){AddFollower();}

                        //if followerLimit reached
                        //cannot add more followers
                        //(sets to true)
                        if(followerLimit == 10){

                        reachedFollowerLimit = true;

                        Context context = getApplicationContext();
                        CharSequence toastText = "Follower limit reached";
                        int duration = Toast.LENGTH_SHORT;

                        Toast toast = Toast.makeText(context, toastText, duration);
                        toast.show();

                        }//end if()
                    break;
                }//END SWITCH

            }//End OnCLICK





        //Adds to followerLimit/Increments followerCount
        //everytime button is clicked
        public final void AddFollower()
            {

            followerLimit++;
            followerCount++;

            }//End AddFollower

        /*Ignore this

        private class Follower
            {
                int influence;

                public Follower(int influence)
                    {
                    influence = 1;

                    }

            }



        public void startWorshipping()
            {


            }

        */


    }//End MainActivity

Here is the main.xml if you need to see the layout.

  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="#ECECEC">

    <LinearLayout
        android:layout_height="80dp"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:gravity="center">

        <Button
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:text="Milestones"
            android:background="#FFFFFF"
            android:textSize="10sp"
            android:singleLine="true"
            android:id="@+id/milestones"
            android:onClick="onClick"/>

        <View
            android:background="?android:attr/dividerHorizontal"
            android:layout_height="match_parent"
            android:layout_width=".5dp"/>

        <Button
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:text="God Stats"
            android:background="#FFFFFF"
            android:textSize="10sp"
            android:singleLine="true"
            android:id="@+id/godStats"
            android:onClick="onClick"/>

        <View
            android:background="?android:attr/dividerHorizontal"
            android:layout_height="match_parent"
            android:layout_width=".5dp"/>

        <Button
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:text="Influence Stats"
            android:background="#FFFFFF"
            android:textSize="10sp"
            android:singleLine="false"
            android:padding="3dp"
            android:lines="2"
            android:minLines="2"
            android:textAlignment="center"
            android:id="@+id/influence"
            android:onClick="onClick"/>

        <View
            android:background="?android:attr/dividerHorizontal"
            android:layout_height="match_parent"
            android:layout_width=".5dp"/>

        <Button
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:text="Followers"
            android:background="#FFFFFF"
            android:gravity="center"
            android:textSize="10sp"
            android:singleLine="true"
            android:id="@+id/followers"
            android:onClick="onClick"/>

    </LinearLayout>

    <View
        android:background="?android:attr/dividerVertical"
        android:layout_height="4dp"
        android:layout_width="match_parent"/>

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <TextView
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_width="wrap_content"
            android:text="Follower Feed"
            android:padding="4dp"/>

        <Button
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:text="Create Follower"
            android:layout_marginLeft="36dp"
            android:layout_marginRight="5dp"
            android:textSize="10sp"
            android:id="@+id/createFollowerButton"
            android:onClick="onClick"/>

    </LinearLayout>

    <View
        android:background="?android:attr/dividerVertical"
        android:layout_height="1dp"
        android:layout_width="match_parent"/>

    <TextView
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_width="match_parent"
        android:text="Create a new follower"
        android:paddingLeft="5dp"
        android:id="@+id/textview1"
        android:paddingTop="6dp"/>

</LinearLayout>

This followerCount variable will be displayed in a TextView in my followers.xml file as follows:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:orientation="horizontal">

        <TextView
            android:layout_height="60dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="wrap_content"
            android:text="Follower Count"
            android:gravity="left|center"
            android:textSize="30sp"
            android:padding="10dp"/>

        <View
            android:background="?android:attr/dividerHorizontal"
            android:layout_height="match_parent"
            android:layout_width="2dp"/>

        <TextView
            android:layout_height="match_parent"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:text="0"
            android:gravity="center_vertical|center_horizontal"
            android:textSize="30sp"
            android:id="@+id/followerCount"/>

    </LinearLayout>

</LinearLayout>

And here's the Java file for followers.xml

package com.couchmango.godslife;

import android.annotation.*;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;

public class followers extends Activity implements OnClickListener
    {
        @Override
        protected void onCreate(Bundle savedInstanceState)
            {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.followers);




            };//End onCreate


        //Saves screen results when back button pressed
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public Intent getParentActivityIntent()
            {
            return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            }



        @Override
        public void onClick(View p1)
            {


            // TODO: Implement this method
            }
    }

My question is: How do I make the TextView in followers.xml increment by 1 each time the Create Followers button in the MainActivity is clicked?

I do not want the button to redirect me to the activity once I click the button.

You're halfway there, you're sending the followerCount int (which shouldn't be static) in the intent to the followers activity as an extra.

In the followers activity, on the onCreate method you need to write something like the following:

Bundle extras = getIntent().getExtras();
    if (extras == null) {
    return;
}
int followerCount = extras.getInt("FollowerCount"); 
    // assign followerCount to a member variable in your followers activity
}

You have to istantiate the textview inside the activity in this way

TextView followerCountTextView = (TextView)findViewById(R.id.followerCount);

then, inside the onClick of the button you can set the number

followerCountTextView.setText("" + followerCount);

I've finally figured it out!

I ended up having to use this code:

public static boolean buttonIsClicked;
public static Bundle bundle = new Bundle();

And this is what I had for the button clicks

@Override
    public void onClick(View v)
        {
        Intent i=new Intent(MainActivity.this, followers.class);
        switch(v.getId()){

                //Milestones Button Pressed
                //Goes to Milestones activity
                case R.id.milestones:Intent intent = new Intent(MainActivity.this, milestones.class);
                MainActivity.this.startActivity(intent);
                break;

                //God Stats Button Pressed
                //Goes to God Stats activity
                case R.id.godStats:intent = new Intent(MainActivity.this, godStats.class);
                MainActivity.this.startActivity(intent);
                break;

                //Influence Button Pressed
                //Goes to Influence activity
                case R.id.influence:intent = new Intent(MainActivity.this, influence.class);
                MainActivity.this.startActivity(intent);
                break;

                //Followers Button Pressed
                //Goes to Followers activity
                case R.id.followers:

                followerCount = (TextView)findViewById(R.id.followerCount);

                bundle.putInt("followers",followerCountInt); //This is for an int
                i.putExtras(bundle);
                startActivity(i);
                break;

                //Create Follower Button Pressed
                //Increases followerCount & adds to followerLimit
                //if followerLimit is not reached
                case R.id.createFollowerButton: 

                followerCount = (TextView)findViewById(R.id.followerCount);
                bundle = new Bundle();
                bundle.putInt("followers",followerCountInt); //This is for an int
                i.putExtras(bundle);


                    if(reachedFollowerLimit == false){AddFollower();}

                    //if followerLimit reached
                    //cannot add more followers
                    //(sets to true)
                    if(followerLimit == 10){


                    reachedFollowerLimit = true;

                    Context context = getApplicationContext();
                    CharSequence toastText = "Follower limit reached";
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(context, toastText, duration);
                    toast.show();

                    }//end if()
                break;
            }//END SWITCH

        }//End OnCLICK

This is what I had for the followers.class file

    package com.couchmango.godslife;

import android.annotation.*;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;

public class followers extends Activity implements OnClickListener
    {
        TextView followerCount;

        @Override
        protected void onCreate(Bundle savedInstanceState)
            {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.followers);

            followerCount = (TextView)findViewById(R.id.followerCount);

            if(MainActivity.buttonIsClicked==false)
            {
            Bundle bundle = null;
            bundle = this.getIntent().getExtras();
            int myInt = bundle.getInt("followers");//this is for an int
            followerCount.setText(String.valueOf(myInt));
            }

            };//End onCreate

The way i have this set up, basically clicking the Create Follower , it runs the intent that increments the textview, but doesn't actually open the followers.java activity.

But at the same time, if you click the Followers button, it only displays the followers.xml file, not incrementing anything.

This is exactly what I was looking to do, and I finally have figured it out after playing with some of the code provided!

Thanks guys! Been stuck on this one for about 2 weeks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM