Android 单击按钮,在同一活动中维护或更改值
在代码中,我将新值传递给同一个活动(OneActivity),但当我单击按钮时,似乎会打开一个新活动(刷新屏幕)。如何修改下面的thr代码以维护活动,而不是在单击按钮时刷新活动Android 单击按钮,在同一活动中维护或更改值,android,Android,在代码中,我将新值传递给同一个活动(OneActivity),但当我单击按钮时,似乎会打开一个新活动(刷新屏幕)。如何修改下面的thr代码以维护活动,而不是在单击按钮时刷新活动 final Button fruit_q = (Button) findViewById(R.id.fruit_q); fruit_q.setOnClickListener(new OnClickListener() //Next step { public void onClic
final Button fruit_q = (Button) findViewById(R.id.fruit_q);
fruit_q.setOnClickListener(new OnClickListener() //Next step
{
public void onClick(View v)
{
Intent i = new Intent(getApplicationContext(), OneActivity.class);
if(position != 35) //35 is end of index in gridview array
{
// passing array index
String name = getResources().getResourceEntryName(imageAdapter.mThumbIds[position+1]);
i.putExtra("image_name", name);
i.putExtra("id", position+1);
i.putExtra("rememberID_frist", firstTimeID_1);
i.putExtra("rememberID_second", position+1);
whatfruit.stop();
correctAnswer.stop();
}
else // ber sin chea answer dol index 35 hery jang back to index 0
{
// passing array index
//String name = getResources().getResourceEntryName(imageAdapter.mThumbIds[position+1]);
i.putExtra("image_name", "apple");
i.putExtra("id", 0);
i.putExtra("rememberID_frist", firstTimeID_1);
i.putExtra("rememberID_second", 0);
whatfruit.stop();
}
startActivity(i);
}
});
谢谢 似乎您只想在单击按钮时增加位置值,而位置不是35。由于您将四个值作为IntentExtras传递,请尝试以下操作: 创建作为附加值传递的四个值,并在活动中作为全局变量传递。 在
onCreate()
中,您可以将传递的值分配给此变量(例如位置)。然后,在onClickListener
中所要做的就是
fruit_q.setOnClickListener(new OnClickListener() //Next step
{
public void onClick(View v)
{
if(position != 35) //35 is end of index in gridview array
{
id = position + 1;
secondID = position + 1;
}
else // ber sin chea answer dol index 35 hery jang back to index 0
{
id = 0;
secondID = 0;
}
// call method to show this new values (1)
}
});
(1)中提到的方法可以设计为设置活动的所有视觉和背景计算内容,以便可以从onCreate()
和onClickListener
调用
示例
public class MyActivity extends Activity{
// ...
private int a, b, c;
protected void onCreate(Bundle b){
// do usual stuff
a = getIntent().getIntExtra("a");
b = getIntent().getIntExtra("b");
c = getIntent().getIntExtra("c");
// ...
fruit_q.setOnClickListener(new OnClickListener(){
public void onClick(View v){
a += 1;
b += 2;
c -= 3;
displayStuff();
}
}
displayStuff();
}
private void displayStuff(){
// get displaying components like TextView
// set some of the values like a, b or c as Text
}
// ...
}
我没有直接检查这个代码,它应该只是告诉你我的意思是原则。这样,您就可以直接在活动中操作现有值,而无需刷新它。您可能需要共享首选项如果您创建了一个意图并调用startActivity(i),那么活动显然会被刷新。您可能需要在onClick()中更改全局变量。亲爱的Valentino,请修改我的代码,因为我已经尝试了2个小时,但仍然找不到解决方案。您对活动中的值做了什么?@user1731690我感到困惑。改变什么价值?