我想创建一个自定义搜索栏,该搜索栏出现在我的应用程序顶部,可用于搜索对象列表中的项目。...这些对象被绘制到地图上,并且还有一个列表textview,其中所有的信息都会显示出来。用户可以在地图视图和列表视图之间切换...我已经尝试过给出一些想法,但是没有用,将不胜感激。
mainActivity
package com.vuvucall.maptest;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
GoogleMap googleMap;
ArrayList<Item> mItems = new ArrayList<>();
FrameLayout mapsLayout;
Button loadDataButton;
boolean listLoad = true;
LinearLayoutManager linearLayoutManager;
RecyclerView recycleView;
ListDataAdapter listDataAdapter;
ListView listView;
EditText editText;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
linearLayoutManager = new LinearLayoutManager(context);
// EditText editText = findViewById((R.id.search_text));
//
// editText.addTextChangedListener(new TextWatcher() {
// @Override
// public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// }
// @Override
// public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// }
// @Override
// public void afterTextChanged(Editable editable)
// {
// //filter(editable.toString());
// }
// });
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapsLayout = findViewById(R.id.mapsLayout);
loadDataButton = findViewById(R.id.loadDataButton);
recycleView = findViewById(R.id.recycleView);
recycleView.setLayoutManager(linearLayoutManager);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
loadDataButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listLoad) {
listLoad = false;
mapsLayout.setVisibility(View.VISIBLE);
recycleView.setVisibility(View.GONE);
loadMapsData(mItems);
loadDataButton.setText(getString(R.string.show_list));
} else {
listLoad = true;
mapsLayout.setVisibility(View.GONE);
recycleView.setVisibility(View.VISIBLE);
loadListData(mItems);
loadDataButton.setText(getString(R.string.show_maps));
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
new ProcessInBackground().execute();
}
public class ProcessInBackground extends AsyncTask<Integer, Void, ArrayList<Item>> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
Exception exception = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Busy loading rss feed...please wait...");
progressDialog.show();
}
@Override
protected ArrayList<Item> doInBackground(Integer... params) {
try {
URL url = new URL("http://quakes.bgs.ac.uk/feeds/MhSeismology.xml");
//creates new instance of PullParserFactory that can be used to create XML pull parsers
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//Specifies whether the parser produced by this factory will provide support
//for XML namespaces
factory.setNamespaceAware(false);
//creates a new instance of a XML pull parser using the currently configured
//factory features
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* We should take into consideration that the rss feed name is also enclosed in a "<title>" tag.
* Every feed begins with these lines: "<channel><title>Feed_Name</title> etc."
* We should skip the "<title>" tag which is a child of "<channel>" tag,
* and take into consideration only the "<title>" tag which is a child of the "<item>" tag
*
* In order to achieve this, we will make use of a boolean variable called "insideItem".
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, START_DOCUMENT, END_DOCUMENT etc..
int eventType = xpp.getEventType(); //loop control variable
Item item = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
//if we are at a START_TAG (opening tag)
if (eventType == XmlPullParser.START_TAG) {
//if the tag is called "item"
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
item = new Item();
}
//if the tag is called "title"
else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem) {
// extract the text between <title> and </title>
item.setTitle(xpp.nextText());
}
}
//if the tag is called "link"
else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem) {
// extract the text between <link> and </link>
item.setLink(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("geo:lat")) {
if (insideItem) {
//extract the text between <geo:lat> and </geo:lat>
item.setLat(Double.valueOf(xpp.nextText()));
}
} else if (xpp.getName().equalsIgnoreCase("geo:long")) {
if (insideItem) {
//extract the text between <geo:lat> and </geo:lat>
item.setLon(Double.valueOf(xpp.nextText()));
}
}
}
//if we are at an END_TAG and the END_TAG is called "item"
else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
mItems.add(item);
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
exception = e;
} catch (XmlPullParserException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return mItems;
}
@Override
protected void onPostExecute(ArrayList<Item> s) {
super.onPostExecute(s);
// ArrayAdapter<Item> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, mItems);
// lvRss.setAdapter(adapter);
progressDialog.dismiss();
loadDataButton.setVisibility(View.VISIBLE);
loadListData(s);
}
}
public InputStream getInputStream(URL url) {
try {
//openConnection() returns instance that represents a connection to the remote object referred to by the URL
//getInputStream() returns a stream that reads from the open connection
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
private void loadMapsData(ArrayList<Item> listData) {
int i = 0;
for (Item item : listData) {
if (i % 5 == 0) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
} else if (i % 5 == 1) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
} else if (i % 5 == 2) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
} else if (i % 5 == 3) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
} else if (i % 5 == 4) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(item.getLat(), item.getLon()))
.title(item.getTitle())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
}
i++;
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
//the include method will calculate the min and max bound.
for (Item item : listData) {
builder.include(new LatLng(item.getLat(), item.getLon()));
}
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
int padding = (int) (width * 0.10); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
googleMap.animateCamera(cu);
}
private void loadListData(ArrayList<Item> listData) {
listDataAdapter = new ListDataAdapter(context, listData);
recycleView.setAdapter(listDataAdapter);
}
}
item.java
package com.vuvucall.maptest;
public class Item {
private String title;
private String link;
private Double lat;
private Double lon;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
@Override
public String toString() {
return (new StringBuilder()).append("title: \n").append(title).append("\n")
.append("link: ").append(link).append("\n")
.append("geo-lat: ").append(lat).append("\n")
.append("geo-lon: ").append(lon).toString();
}
}
item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/rootView"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#f4ffe7"
android:layout_margin="2dp"
>
<TextView
android:padding="5dp"
android:text="Title"
android:textColor="#000000"
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:padding="5dp"
android:text="23.4, 34.8"
android:textColor="#000000"
android:id="@+id/latlon"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
ListAdapter.java
package com.vuvucall.maptest;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ListDataAdapter extends RecyclerView.Adapter<ListDataAdapter.MyViewHolder> {
private Context context;
public ArrayList<Item> itemList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
}
}
@Override
public int getItemViewType(int position) {
// two types of view. One is title of group and other is item view
return position;
}
public ListDataAdapter(Context context,ArrayList<Item> events) {
this.context = context;
this.itemList =events;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View viewTWO = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
MainViewImage rowTWO = new MainViewImage(viewTWO);
return rowTWO;
}
public class MainViewImage extends MyViewHolder {
LinearLayout rootView;
TextView title,latlon;
public MainViewImage(View v) {
super(v);
rootView = (LinearLayout) v.findViewById(R.id.rootView);
title = (TextView) v.findViewById(R.id.title);
latlon = (TextView) v.findViewById(R.id.latlon);
}
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final Item event= itemList.get(position);
final MainViewImage mainHolder = (MainViewImage)holder;
mainHolder.title.setText(event.getTitle());
mainHolder.latlon.setText("Latitude: "+event.getLat()+" , Longitude: "+event.getLon());
}
@Override
public int getItemCount() {
return itemList.size();
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<EditText
android:id="@+id/search_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:gravity="right"/><!--gravity of a edit text-->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:visibility="gone"
android:layout_alignParentRight="true"
android:text="@string/show_maps"
android:id="@+id/loadDataButton"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
<include android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/toolbar" layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:src="@android:drawable/ic_dialog_info" />
</RelativeLayout>
我已经创建了一个编辑文本对象,并且尝试创建一个可以在项目列表中进行搜索的函数,但是我一直遇到不兼容问题,因此我在主要活动中的所有代码都出现了错误..我很困惑。 / p>