![](/img/trans.png)
[英]android studio - how to get text from one activity to another?
[英]Get Text from one Acitivity to another Activity
我必须进行“ Main”和“ Shop”活动,并且在“ Shop”中有一个变量,我想在“ Main” -Activity中使用该变量,我该怎么做? 感谢帮助。 我想在我的“ Main”类中添加intCountValue2。 那是我的整个商店代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_shop);
btnBuyClickMultiplier = (Button) findViewById(R.id.ClickMultiplierButton);
txtMultiplierCounter= (TextView) findViewById(R.id.ClickMultiplier);
btnBuyClickMultiplier.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String CountValue2= txtMultiplierCounter.getText().toString();
int intCountValue2 = Integer.parseInt(CountValue2);
intCountValue2++;
txtMultiplierCounter.setText(String.valueOf(intCountValue2));
}
});
configureBackButton1();
}
private void configureBackButton1() {
Button BackButton1 = (Button) findViewById(R.id.BackButton1);
BackButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
最简便但并非最佳的方法是,将变量“ shop”声明为public和static,如下所示:
public static String shop;
然后,您可以在Main活动中按如下方式调用该变量:
ShopActivity.shop;
在开始Android编程之前,您必须对面向对象编程有充分的了解。 但是,要解决您的问题,您可以尝试使用Getter and Setter method
概念(在这种情况下,只需要使用getter)。 为此,请在您的特定情况下:
首先,在Shop
类中声明一个私有变量(显然在任何方法之外,例如onCreate()
左右),如下所示:
private int count;
然后,在Shop
类中创建一个公共方法,如下所示:
public int getCount() { return this.count; }
现在,在Shop
类的onCreate()
方法中,在setOnClickListener
的btnBuyClickMultiplier
,将count
的值设置为intCountValue2
如下所示:
btnBuyClickMultiplier.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String CountValue2= txtMultiplierCounter.getText().toString(); int intCountValue2 = Integer.parseInt(CountValue2); intCountValue2++; txtMultiplierCounter.setText(String.valueOf(intCountValue2)); count = intCountValue2; } });
最后,您可以从在Main
类内部创建的Shop
类的实例访问intCountValue2
变量的值,如下所示:
Shop s = new Shop(); int intCountvalue2 = s.getCount();
希望你能理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.