如何在android studio中为onClick块中的先前定义的字符串赋值

时间:2017-03-29 11:44:17

标签: java android string

所以我有2个活动通过意图相互链接,但我需要第二页知道在上一页中点击了什么。这是我的意思。

public class featuredvendors extends AppCompatActivity {


public String nextpageref;

我想编辑的字符串在上面声明。

t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);

            startActivity(t2);
        }
    });

基本上,我想根据点击的内容更改nextpageref的值。但是,似乎我无法更改onClick块中的值。无论如何我可以传递价值" post1"到字符串,但只有在单击此特定按钮时?我需要这种方式,因为下一页特色详细说明'需要知道这个String值才能从DB中提取正确的信息。

2 个答案:

答案 0 :(得分:0)

onClick块中添加此

t2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            nextpageref="post1";
            Intent t2 = new Intent(featuredvendors.this, featureddetails.class);
t2.putString("key", nextpageref);
            startActivity(t2);
        }
    });

在下一个活动中,从onCreate方法

中的这段代码中获取值
Intent i= getIntent();
String value = i.getStringExtra("key");
Log.e("value", value);

答案 1 :(得分:0)

<强> SendingActivity

   Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
    intent. putString("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
    startActivity(intent); 

Second Screen.java

public class newclass extends Activity {     私有TextView Textv;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.intent);
    Textv = (TextView)findViewById(R.id.tv2);
    Intent i= getIntent();
    i.getStringExtra("keyName");
}

}