Pass value outside of public void onClick

2019-06-14 01:26发布

So im sure this is probably a fairly easy question but I am stumped because I am a beginner.

I am looking to pass a value from one class to another, and I have my helper function down and working just fine. If i create an integer outside of my onClick I can pass it no problem. If I create it inside the onClick though it doesn't seem to make it out.

package com.movi.easypar;

//import java.util.logging.Handler;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class EntryScreen extends Activity implements OnClickListener {

Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; <--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.entryscreen);


    //******************//
    //***DEFINE FONTS***//
    //******************//
    Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");

    //*****************************************************//
    //***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
    //*****************************************************//
    buttonSetHoles = (Button)findViewById(R.id.buttonSetHoles);
    buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
    buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
    textGameSetup = (TextView)findViewById(R.id.textGameSetup);
    buttonSetHoles.setTypeface(merge);
    buttonSetPlayers.setTypeface(merge);
    buttonLetsGo.setTypeface(merge);
    textGameSetup.setTypeface(merge);
    buttonSetHoles.setText("Set Holes");
    buttonLetsGo.setText("Lets Go");
    buttonSetPlayers.setText("Set Players");

    //******************************//
    //***DEFINES BUTTON LISTENERS***//
    //******************************//
    buttonSetHoles.setOnClickListener(this);
    buttonSetPlayers.setOnClickListener(this);
    buttonLetsGo.setOnClickListener(this);
}






//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
@Override
public void onClick(View src) {

    switch(src.getId()){

    case R.id.buttonSetPlayers:
        break;

    case R.id.buttonSetHoles:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final CharSequence[] items = {"18", "9"};
        builder.setTitle("Set Holes");
        builder.setItems(items, new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialogInterface, int item) {
                Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                if (items[item].equals("9")){
                    EntryScreen.this.setHoles = 9; <---#### VALUE SET HERE ####

                }
                else if (items[item].equals("18")){
                    EntryScreen.this.setHoles = 18;

                }

                return;
            }
        });
        builder.create().show();

        return;

    case R.id.buttonLetsGo:
        //*********************************//
        //***LAUNCHES ACTUAL APPLICATION***//
        //*********************************//
        TranslateAnimation slide = new TranslateAnimation(0, -500, 0,0 );
        slide.setDuration(1000);   
        slide.setFillAfter(true);
        buttonLetsGo.startAnimation(slide);
        buttonSetPlayers.startAnimation(slide);
        buttonSetHoles.startAnimation(slide);
        Intent myIntent = new Intent(src.getContext(), EasyPar.class);
        startActivityForResult(myIntent, 0);
        break;
    }
    EntryScreen.this.finish();
}   


public String getNames() {
    return name1;
}

public void setNames(String playerName1) {
    name1 = playerName1;
}

public int getHoles() {
    return setHoles;  <---- #### THIS DOES NOT SEE VALUE SET IN ONCLICK ####
}
}

This helper does not seem to be able to see the setHoles value that is created onClick.

Any suggestions? Thanks in advance!

5条回答
贪生不怕死
2楼-- · 2019-06-14 01:38

are you sure your setHoles is even being set? to 9 or 18? try adding a println(setHoles) in your onclick to ensure that the value is being set properly. Also, you are declaring your setHoles variable outside of onCreate but within the same class as getHoles() and onClick() right?

查看更多
女痞
3楼-- · 2019-06-14 01:48

Declare it as public/private variable outside the methods.

查看更多
一纸荒年 Trace。
4楼-- · 2019-06-14 01:54

It's a scope thing. A variable defined in a function has local scope, and will be destroyed when the function returns. You need a field to hold your value if you wish to retain it.

[EDIT]
Then allow me to elaborate. You can create a field by typing the following line outside a function, inside the class:

[Access][Type][Name];

ex:

class foo{
    public int dice;
    public void onClick(){
         //now the dice's value is saved throught the lifecycle of the Activity
    }
}

[EDIT] I copied your code and ran it. (Modified just a little.)

public class Main extends Activity implements OnClickListener {

Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; //<--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //******************//
    //***DEFINE FONTS***//
    //******************//
    Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");

    //*****************************************************//
    //***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
    //*****************************************************//
    /*

    buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
    buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
    textGameSetup = (TextView)findViewById(R.id.textGameSetup);
    */
    buttonSetHoles = (Button) findViewById(R.id.buttonSetHoles);
    /*
    buttonSetHoles.setTypeface(merge);
    buttonSetPlayers.setTypeface(merge);
    buttonLetsGo.setTypeface(merge);
    textGameSetup.setTypeface(merge);
    buttonSetHoles.setText("Set Holes");
    buttonLetsGo.setText("Lets Go");
    buttonSetPlayers.setText("Set Players");
    */

    //******************************//
    //***DEFINES BUTTON LISTENERS***//
    //******************************//.
    buttonSetHoles.setOnClickListener(this);
    /*
    buttonSetPlayers.setOnClickListener(this);
    buttonLetsGo.setOnClickListener(this);
    */
}

//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
@Override
public void onClick(View src) {

    switch (src.getId()) {

        case R.id.buttonSetHoles:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            final CharSequence[] items = { "18", "9" };
            builder.setTitle("Set Holes");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int item) {
                    Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                    if (items[item].equals("9")) {
                        setHoles = 9;// <---#### VALUE SET HERE ####
                        Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
                    }
                    else if (items[item].equals("18")) {
                        setHoles = 18;
                        Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
                    }

                    return;
                }
            });
            builder.create().show();

            return;

    }
    //finish();
}

public String getNames() {
    return name1;
}

public void setNames(String playerName1) {
    name1 = playerName1;
}

public int getHoles() {
    return setHoles;
}
}

And it seems to work just fine.

查看更多
Bombasti
5楼-- · 2019-06-14 01:59

If you declare the variable inside the method, an external method is surely not able to see it, it's not in the same scope, you can still declare it outside and then set a value from inside the onClick() method.

查看更多
手持菜刀,她持情操
6楼-- · 2019-06-14 02:00

when you compare Strings always use equal method. like:

  if (items[item].equals( "9")){
}

and i prefer to user Setters and Getters on variables:

setHoles(int value){}

and

int getHoles(){}

查看更多
登录 后发表回答