将rand变量从一个类传递到另一个具有相同值的类

时间:2017-03-22 01:12:40

标签: java android variables random

尝试在一个类中传递一个随机生成的变量,以便在另一个类中使用,以同步我的应用程序的背景和另一个片段中的标题。

public class LoginMain extends AppCompatActivity {
    RelativeLayout loginMain;
    Random rand = new Random();
    int bgPick = rand.nextInt(5) + 1; //distribute int from 1 to 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);
        //must be called after the content view is set.
        loginMain = (RelativeLayout) findViewById(R.id.activity_login_main);
        randomBG();//method that determines the background image based on the bgPick value.
    }

    public static int getBgPick(){
        return bgPick;
    }

主类:

public class MainActivity extends AppCompatActivity {
    AppBarLayout appBarLayout;
    int bgPick = LoginMain.getBgPick();


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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        randomHeader();//method to determine header image based on bgPick value determined in the LoginMain class.

这导致产生两个bgPick值并在每个类中单独使用。

2 个答案:

答案 0 :(得分:0)

您应该考虑使用 intent 例如,如果要将项目从一个类传递到另一个类。

 Intent intent =new Intent(FirstActivity.this,SecondAcitivity.class);
 intent.putExtra("EXTRA_SESSION_ID", sessionId);
 intent.putExtra("EXTRA_String", "California");
 startActivity(intent);

在SecondActivity中;

String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
String place = getIntent().getStringExtra("EXTRA_String");

答案 1 :(得分:-1)

使用StaticgetBgPick方法解决。

public class LoginMain extends AppCompatActivity {
    RelativeLayout loginMain;
    Random rand = new Random();
    public static int bgPick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);
        this.bgPick = rand.nextInt(5) + 1; //distribute int from 1 to 3
        //must be called after the content view is set.
        loginMain = (RelativeLayout) findViewById(R.id.activity_login_main);
        randomBG();
    }

    public static int getBgPick(){
        return bgPick;
    }
}

主要类别:

public class MainActivity extends AppCompatActivity {    
    AppBarLayout appBarLayout;
    int bgPick = LoginMain.getBgPick();


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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        randomHeader();
    }
}