从XML填充的Android ListView不会将数据发送到新活动

时间:2021-08-02 03:46:23

I have an array located in my strings.xml file that looks like the following.

我有一个位于strings.xml文件中的数组,如下所示。

<string-array name="array123">
<item>test1</item>
<item>test2</item>
<item>test3</item>
<item>test4</item>
<item>test5</item>
</string-array>

My listview is properly displayed on Activity 1, here is my onItemClick code

我的listview在Activity 1上正确显示,这是我的onItemClick代码

public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent activityIntent = new Intent(this, Activity2.class);
String selectedItem = adapter.getSelectedItem().toString();
activityIntent.putExtra("my.package.dataToPass", selectedItem);
startActivity(activityIntent);

As soon as I tap an item from the list the screen just goes black and the application crashes. Here is my code for Activity 2

一旦我从列表中点击一个项目,屏幕就会变黑并且应用程序崩溃。这是我的活动2的代码

Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("my.package.dataToPass");
TextView word = (TextView) findViewById(R.id.word);
word.setText(myVal);

I'm not sure why this isn't working. I'm just trying to pass the string that was selected to show as text on the 2nd activity. I've been searching for a day and a half now. I did try

我不确定为什么这不起作用。我只是想传递选中的字符串,以便在第二个活动中显示为文本。我一直在寻找一天半。我确实试过了

activityIntent.putExtra("my.package.dataToPass", id);

but this just seemed to pass an empty screen. Any help would be much appreciated. Obviously I'm not passing the right data in the intent.

但这似乎只是通过一个空屏幕。任何帮助将非常感激。显然我没有在意图中传递正确的数据。

1 个解决方案

#1


0  

As I can see, you are implementing the Click listener (onItemClick) rather than Select listener(onItemSelected). By default when you click on a ListView item it doesn't change its state to "selected"

正如我所看到的,您正在实现Click侦听器(onItemClick)而不是Select侦听器(onItemSelected)。默认情况下,当您单击ListView项时,它不会将其状态更改为“已选择”

Plz use adapter.getItem(position) instead of adapter.getSelectedItem()

Plz使用adapter.getItem(position)而不是adapter.getSelectedItem()

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    String selectedItem  = adapter.getItem(position).toString();
}

#1


0  

As I can see, you are implementing the Click listener (onItemClick) rather than Select listener(onItemSelected). By default when you click on a ListView item it doesn't change its state to "selected"

正如我所看到的,您正在实现Click侦听器(onItemClick)而不是Select侦听器(onItemSelected)。默认情况下,当您单击ListView项时,它不会将其状态更改为“已选择”

Plz use adapter.getItem(position) instead of adapter.getSelectedItem()

Plz使用adapter.getItem(position)而不是adapter.getSelectedItem()

public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    String selectedItem  = adapter.getItem(position).toString();
}