Activity intent传值,在get方法中为什么只取到了private int 的原始值

问题:在前一个Activity中设置了传值row和column=4或6,经过测试到mainActivity传值成功。当在gameView中取getRow的值时,每次只取到private中的值6,而不取传过的intent中的值。

代码如下:

public class MainActivity extends Activity {
private int row = 6;
private int column= 6;
public MainActivity() {
mainActivity = this;
}

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvscore = findViewById(R.id.tvScore);
Intent intent = this.getIntent();
row = intent.getIntExtra("row", 4);
column = intent.getIntExtra("column", 4);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void clearScore() {
score = 0;
showScore();
}

private void showScore() {
// TODO Auto-generated method stub
// if(int s = getMax(CardMap[x][y])){
//
// }
tvscore.setText(score + "");

}

public void addScore(int s) {
score += s;
showScore();
}

private TextView tvscore;
private int score = 0;
public static MainActivity mainActivity = null;

public static MainActivity getMainActivity() {
return mainActivity;
}

public int getColumn() {
return column;
}

public int getRow() {
return row;
}
}

GameView中的部分代码:

private int row, column;
private Cards[][] cardMap = new Cards[10][10];
private ArrayList emptyPoints = new ArrayList<>();

public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initGame();
}

public void initGame() {
// TODO Auto-generated method stub
row = MainActivity.getMainActivity().getRow();
column = MainActivity.getMainActivity().getColumn();
setColumnCount(column);
setBackgroundColor(getResources().getColor(R.color.grey3));

求大神解答!!!谢谢谢谢!!!

你在activity setContentView的时候就会触发gameview initGame方法。这时候row column 还没有被赋值为你传递的值还是默认值6.所以一直拿到都是默认值。

我觉得是静态的public static MainActivity mainActivity = null的问题。为什么用这种方法传递数值啊,直接用intent不好吗

你这是咋搞出来,静态方法居然能够返回不是静态的变量

如果想要存储值,你通过使用SharedPreferences存储