난 아직 초보자 프로그래머이고, 나는 당신보다 더 많은 전문가와 나보다 스마트 : 나는 itemClickListener에 문제가있어, 왜 나도 몰라.하지만 난 모두 올바르게 설정하지만 내 앱을 실행하고 항목을 터치하려고하면 리스너가 응답하지 않고 아무 것도하지 않습니다 ... 나를 도울 수 있고 제 영어에 대해 사과 할 수 있습니다. 아직 개선 중입니다. 그것 ...안드로이드 ListView onItemClickListener 아무것도하지 않습니다
만약 내가 당신이 improvment에 대한 제안이 있다면 나는 코드를 작성하는 무한히 감사 할 것입니다 !!!
코드 - 청취자 :
@Override
public void updateUI(ArrayList<Place> placeList) {
placesFound = placeList;
PlacesAdapter adapter = new PlacesAdapter(this, placesFound);
placesListView.setAdapter(adapter);
placesListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.d("USER", "Item clicked");
}
});
if (placeList.size() == 0)
Toast.makeText(this, getString(R.string.no_results_found), Toast.LENGTH_LONG).show();
}
코드 - 모든 클래스 : 각 행에 클릭 리스너에 대한 adapter
의 getView
에서
public class CategoryResultsActivity extends Activity implements ChangeDataInterface {
// Take the category name from the Intent and use
// it to retrive data using the category anme itself and other parameters
// not asked to the user directly, but using defaults one.
// If the user want to change this parameters, it can with the spinners in the page
// The data retrived will be in an xml format and parsed inside this class.
// Category used to make a request to the server using it as filter,
// get only data fpr the selected category.
private String category = "bar";
// Location used to search places of the category within a radius
// Location expressed in longitude, latitude. To retrive this informations
// it will be used a service that give this informations using a city name
// If the user want to search places using its position, the service will
// use the geolocation inside the phone.
// Order: latitude, longitude
private String latitude = "45.070562",
longitude = "7.686619";
// Defines the distance (in meters) within which to return Place results. The maximum allowed radius is 50 000 meters.
private String radius = "500";
// Indicates whether or not the Place request came from a device using a location sensor (e.g. a GPS) to determine the
// location sent in this request. This value must be either true or false.
private boolean sensor = false;
// List of the places found with the parsing, keep in memory while parsing all data and,
// once all is finished, show to the user
private ArrayList<Place> placesFound = new ArrayList<Place>();
/*---------- LAYOUT DATA --------------*/
// FrameLayout - Image for the search category
private FrameLayout categoryImageFrameLayout;
// ListView - List of places found from the parsing
private ListView placesListView;
// Spinner for ordering data by the distance,
// used in this case default distance, expressed in meters, like:
// 50m, 100m, 200m, 500m, 1km, 2km, 5km, 10km, 20km, 50km
private Spinner orderByDistanceSpinner;
// View on a map the data found, each place is reported
// on a map using a marker
private Button showOnMapButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_results);
// Initialize the layout data
categoryImageFrameLayout = (FrameLayout) findViewById(R.id.categoryResultsFrameLayout);
placesListView = (ListView) findViewById(R.id.categoryResultsListView);
orderByDistanceSpinner = (Spinner) findViewById(R.id.orderByDistanceSpinner);
showOnMapButton = (Button) findViewById(R.id.showOnMapButton);
// Get data from the intent passed and set the parameters
category = getDataFromIntent(getIntent());
// Get the search category image and set it
categoryImageFrameLayout.setBackgroundResource(getCategoryImage(category));
// When set up spinner download also the data and refresh the UI
setUpSpinner();
// Set the listener for the showOnMapButton, when clicked open a new activity with
// all the places showed on a map using markers
showOnMapButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String[] user = {latitude, longitude};
Intent intent = new Intent(CategoryResultsActivity.this, ShowOnMapActivity.class);
intent.putExtra("places", placesFound);
intent.putExtra("user", user);
startActivity(intent);
}
});
}
// Get data from intent and set data
// The intent will contain the category name
// used in the search
private String getDataFromIntent(Intent intent) {
return intent.getStringExtra(MainActivity.KEY_CATEGORY_NAME);
}
// Get the image relative to the current category and return it
private int getCategoryImage(String category) {
int image = R.drawable.all;
if (category.equals("restaurant")) image = R.drawable.restaurant_header;
else if (category.equals("bar")) image = R.drawable.bar_header;
else if (category.equals("bank")) image = R.drawable.bank_header;
else if (category.equals("book_store")) image = R.drawable.book_store_header;
else if (category.equals("shopping_mall")) image = R.drawable.shopping_mall_header;
else if (category.equals("clothing_store")) image = R.drawable.clothing_store_header;
else if (category.equals("museum")) image = R.drawable.museum_header;
else if (category.equals("library")) image = R.drawable.library_header;
else if (category.equals("bus_station")) image = R.drawable.bus_station_header;
else if (category.equals("park")) image = R.drawable.park_header;
return image;
}
// Update the UI using the data passed, if no results were found
// then set the appropriate background image
@Override
public void updateUI(ArrayList<Place> placeList) {
placesFound = placeList;
PlacesAdapter adapter = new PlacesAdapter(this, placesFound);
placesListView.setAdapter(adapter);
placesListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.d("USER", "Item clicked");
}
});
if (placeList.size() == 0)
Toast.makeText(this, getString(R.string.no_results_found), Toast.LENGTH_LONG).show();
}
private void setUpSpinner() {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.distances, R.layout.simple_spinner_item);
orderByDistanceSpinner.setAdapter(adapter);
orderByDistanceSpinner.setSelection(3); // Select 500 meters as default
orderByDistanceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> container, View view,
int position, long id) {
// Cast the view clicked to a textview and take the text inside
TextView textClicked = (TextView) view;
String text = textClicked.getText().toString();
// If the text has a km measure, then replace it with 3 zero.
// Example: 5km => 5 000
text = text.replace("km", "000");
// If the text also contains a meter measure, remove it
text = text.replace("m", "");
// Set the new radius
radius = text;
// Retrive the data using an asyncTask, so we will use another thread
// in background to download the data, and once complete, set it using the
// onPostExecute method.
downloadData();
}
@Override
public void onNothingSelected(AdapterView<?> container) { }
});
}
// Check if the device is connected to internet
public boolean isOnline() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return manager.getActiveNetworkInfo() != null &&
manager.getActiveNetworkInfo().isConnectedOrConnecting();
}
// Check if the device has an internet connection.
// Internet connection: download data and show a message to the user
// No Internet connection: Show an error message using a toast
private void downloadData() {
// INTERNET
if (isOnline()) {
Toast.makeText(this, R.string.downloading_data, Toast.LENGTH_SHORT).show();
new PlaceSearchTask(this, category, radius, latitude, longitude, sensor).execute();
}
// NO INTERNET
else {
Toast.makeText(this, R.string.internet_connection_error, Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.category_results, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String address) {
// Get the parameters for the address
List<Address> result = null;
try {
result = new Geocoder(getApplicationContext()).getFromLocationName(address, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Check if found results
if (result != null) {
// Search the results
latitude = result.get(0).getLatitude() + "";
longitude = result.get(0).getLongitude() + "";
downloadData();
} else {
Toast.makeText(getApplicationContext(), R.string.address_error, Toast.LENGTH_SHORT).show();
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_search:
return true;
case R.id.action_geolocation:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude() + "";
latitude = location.getLatitude() + "";
downloadData();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Support for the list adapter, optimizing the speed
//keeping in memory some data
class ViewHolder {
private FrameLayout image;
private TextView name,
vicinity;
private RatingBar rating;
public ViewHolder(View view) {
this.image = (FrameLayout) view.findViewById(R.id.singleCatResultImageFrameLayout);
this.name = (TextView) view.findViewById(R.id.singleCatResultTitleTextView);
this.vicinity = (TextView) view.findViewById(R.id.singleCatResultAddressTextView);
this.rating = (RatingBar) view.findViewById(R.id.singleCatResultRatingBar);
}
public FrameLayout getImage() {
return image;
}
public TextView getName() {
return name;
}
public TextView getVicinity() {
return vicinity;
}
public RatingBar getRating() {
return rating;
}
}
class PlacesAdapter extends BaseAdapter {
private Context context;
private ArrayList<Place> places;
public PlacesAdapter(Context context, ArrayList<Place> places) {
this.context = context;
this.places = places;
}
@Override
public int getCount() {
return places.size();
}
@Override
public Object getItem(int index) {
return places.get(index);
}
@Override
public long getItemId(int arg0) {
return 0;
}
@Override
public View getView(int index, View restoreView, ViewGroup container) {
View view = restoreView;
ViewHolder holder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_category_result, container, false);
holder = new ViewHolder(view);
view.setTag(holder);
}
else holder = (ViewHolder) view.getTag();
// Set data for the view using the holder
holder.getImage(). setBackgroundResource(R.drawable.bar_icon);
holder.getName(). setText(places.get(index).getName());
holder.getVicinity(). setText(places.get(index).getVicinity());
String rating = places.get(index).getRating();
if (rating != null)
holder.getRating(). setRating(Float.parseFloat(rating));
else
holder.getRating(). setRating(0f);
return view;
}
}
}
코드가 너무 많음 –
updateUI는 무엇을 재정의하며 언제 호출됩니까? – FWeigl
updateUI가 제대로 작동합니다. 문제는 청취자에게 있습니다 ... –