如何在SecondActivity onItemClick中设置文本

时间:2015-03-08 12:06:16

标签: java android listview

当单击项目时,我需要在SecondActivity中设置文本,但文本必须根据项目而不同。单击项目时我发现错误,但它无法正常工作。你能告诉我如何将第一个活动中的文本设置为第二个吗?

第一项活动:

final String[] setP = { "P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9" };

final ListAdapter theAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, setP);
final ListView theListView = (ListView) findViewById(R.id.theListView2);
theListView.setAdapter(theAdapter);

theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        String itemPicked = "Selected: " + String.valueOf(adapterView.getItemAtPosition(position));
        Toast.makeText(MainActivity.this, itemPicked, Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
        intent.putExtra("newsId", "1");
        MainActivity.this.startActivity(intent);


        String chosen = String.valueOf(adapterView.getItemAtPosition(position));

        if (chosen == "P1") { // doesn't work
            SecondActivity.displayR.setText("EXAMPLE FOR P1");
        } else if (chosen.equals("P2")) { // doesn't work
            SecondActivity.displayR.setText("EXAMPLE FOR P2");
        }
    }
});

和SecondActivity:

public static TextView displayR;

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

    displayR = (TextView) findViewById(R.id.textR);
}

1 个答案:

答案 0 :(得分:0)

你需要将你选择的项目名称放入Intent并在Intent的第二个活动中获取它的名字,如下所示:

第一项活动

theListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        String itemPicked = "Selected: " + String.valueOf(adapterView.getItemAtPosition(position));
        Toast.makeText(MainActivity.this, itemPicked, Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
        intent.putExtra("newsId", "1");


        String chosen = String.valueOf(adapterView.getItemAtPosition(position));

        if (chosen == "P1") { // doesn't work
            intent.putExtra("name", "p1");
        } else if (chosen.equals("P2")) { // doesn't work
            intent.putExtra("name", "p2");
        }

        MainActivity.this.startActivity(intent);
    }
});  

第二项活动

public static TextView displayR;

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

    displayR = (TextView) findViewById(R.id.textR);
    String name = getIntent().getStringExtra("name");
    displayR.setText(name);
}