所以最初我在mainactivity.java中有一个字符串数组,它填充了listview,我可以点击listView中的一个项目,它会打开一个新的活动。我现在用xml字符串数组资源替换了该字符串数组以填充listView。但是现在我无法从listView中选择项目。我希望我解释得那么好。谢谢你的帮助!
package com.example.zach.listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//public static String[] routes = {"Information","Crag Map","Main Wall","1. Shark Bait - 5.9", "2. Rain Check - 5.8", "3. Rain Check Direct - 5.7+",
//"4. Arocknophobia - 5.7", "5. Balls Deep - 5.9+", "6. Jingle Bells - 5.9", "7. Itching to Climb - 5.8-", "8. Hog Nose 5.10+",
//"9. Slab Dance - 5.10", "10. Don't Screw with My Disco - 5.11c"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ListAdapter routeAdapter = new CustomAdapter(this, routes);
//Adapter with refernce to xml string array resourcde
ListAdapter routeAdapter = new CustomAdapter(this, getResources().getStringArray(R.array.routeList));
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// working way for selecting certain listview row from above commented out string array
//String route = String.valueOf(parent.getItemAtPosition(position));
//attempt
String route = String.valueOf(getResources().getStringArray(R.array.routeList)[position]);
if (route == "1. Shark Bait - 5.9") {
Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", "Shark Bait");
startActivity(intent);
}
if (route == "Information") {
Intent intent = new Intent(view.getContext(), RouteDetails.class);
intent.putExtra("route", "Birdsboro Rock Climbing Quarry");
startActivity(intent);
}
}
}
);
}
}
答案 0 :(得分:0)
尝试将数组提取为可在侦听器中访问的final String[]
。
您还需要equals
来比较字符串。
final String[] values = getResources().getStringArray(R.array.routeList);
ListAdapter routeAdapter = new CustomAdapter(this, values);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
routeListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String route = values[position];
if (route.equals("1. Shark Bait - 5.9")) {
Intent intent = new Intent(MainActivity.this, RouteDetails.class);
intent.putExtra("route", "Shark Bait");
startActivity(intent);
}