想要在新活动屏幕中显示存储的名称/值数据

时间:2017-01-30 05:30:42

标签: java android android-intent

我对通过意图存储和检索数据的理解是半熟的,但我不确定的是代码实现。我想要实现的是将存储的数据(名称/值对和bundle对象)传递给MainActivity类的ThirdActivity类。这是我到目前为止所尝试的一个片段(当用户点击a3按钮时,它只显示一个没有字符串的空白页面):

要从中存储要发送到ThirdActivity的数据的MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button a2_button = (Button) findViewById(R.id.a2_button);
        a2_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
               Intent a2intent = new Intent("com.tester.lab.x");
               startActivityForResult(a2intent, 1);
            }
        });

        Button a3_button = (Button) findViewById(R.id.a3_button);
        a3_button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                Intent a3intent = new Intent(v.getContext(), ThirdActivity.class);

                a3intent.putExtra("greeting","my Name");
                startActivity(a3intent);

            }
        });
    }
}

ThirdActivity:

public class ThirdActivity extends AppCompatActivity {

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

        getIntent().getStringExtra("greeting");

    }
}

我如何显示字符串"我的姓名"一旦用户点击ThirdActivity按钮?任何帮助都很棒,谢谢!

1 个答案:

答案 0 :(得分:1)

一切都很好,只需为您获得的值添加String类型,并根据需要使用此String(在TextView其他地方展示..):

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

    EditText text = (EditText) findViewById(R.id.your_textView_id);

    String value = getIntent().getStringExtra("greeting");
    text.setText(value);
}

或者使用Button

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

    EditText text = (EditText) findViewById(R.id.your_textView_id);
    Button three = (Button) findViewById(R.id.your_button_id);

    three.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           String value = getIntent().getStringExtra("greeting");
           text.setText(value);
        }
    });     
}