我从找到的示例中设置了一个列表视图和一个 onclick 侦听器。代码构建良好并运行。单击时,Toast 消息中的项目编号“Position”是正确的,但文本始终显示“Apple”,这是数组中的第一个字符串。我认为 String text = listText.getText().toString(); 行是问题,但所有尝试都无法纠正问题
public class ElsEditTitles extends Activity {
String[] StrLabels = new String[16]; // Store Label names to string
String StrFile;
ListView TitleslistView;
Context context;
ListView listView;
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.els_edit_titles);
context = this;
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_row, R.id.listText, FRUITS);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new ListClickhandler());
}
private class ListClickhandler implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> Adapter, View view,
int position, long arg3) {
TextView listText = (TextView) findViewById(R.id.listText);
String text = listText.getText().toString();
Toast.makeText(context, text + " " + position, Toast.LENGTH_LONG)
.show();
}
}
els_edit_tiles.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
list_view_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textSize="30dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
我通过添加视图来编辑该行,它解决了这个问题。感谢 prijupaul 和 egan
TextView listText = (TextView) view.findViewById(R.id.listText);