er列表视图中的Andr​​oid使用dismissDropDo

er列表视图中的Andr​​oid使用dismissDropDo

本文介绍了如何simpleadapter列表视图中的Andr​​oid使用dismissDropDown()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立我在哪里使用自动完成文本显示搜索谷歌地名的Andr​​oid应用程序。

现在的问题是,我想解雇名单时,我从列表视图中选择任何项目。

下面是我的code -

! oncreateview -

  atvPlaces =(AutoCompleteTextView)findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);atvPlaces.addTextChangedListener(新TextWatcher(){@覆盖
公共无效之前onTextChanged(CharSequence中,诠释开始,INT,INT
计数){
    placesTask =新PlacesTask();
    placesTask.execute(s.toString());
}@覆盖
公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数,
        INT后){
    // TODO自动生成方法存根
}@覆盖
公共无效afterTextChanged(编辑S){
    // TODO自动生成方法存根
}
});/ **一个方法从URL下载JSON数据* /
私人字符串downloadUrl(字符串strUrl)抛出IOException
字符串数据=;
InputStream中的IStream = NULL;
HttpURLConnection类的URLConnection = NULL;
尝试{
    网址URL =新的URL(strUrl);    //创建一个HTTP连接使用网址进行沟通
    URLConnection的=(HttpURLConnection类)url.openConnection();    //连接给url
    urlConnection.connect();    // URL从读取数据
    的IStream = urlConnection.getInputStream();    BR的BufferedReader =新的BufferedReader(新的InputStreamReader(的IStream));    StringBuffer的SB =新的StringBuffer();    串线=;
    而((行= br.readLine())!= NULL){
            sb.append(线);
    }    数据= sb.toString();    br.close();   }赶上(例外五){
    Log.d(异常边下载网址,e.toString());
   }最后{
    iStream.close();
    urlConnection.disconnect();
   }
   返回的数据;
   } //获取来自GooglePlaces自动完成Web服务的所有地方
 私有类PlacesTask扩展的AsyncTask<弦乐,太虚,字符串> { @覆盖
 保护字符串doInBackground(字符串...的地方){
//为从Web服务存储数据
字符串数据=;//获得HTTPS浏览器键://$c$c.google.com/apis/console
字符串键=钥匙;字符串输入=;尝试{
    输入=输入=+ URLEn coder.en code(地方[0],UTF-8);
    输入= input.replaceAll(,%20);
}赶上(UnsupportedEncodingException E1){
    e1.printStackTrace();
}
//要搜索的地方类型
字符串类型=类型=地理code;//启用传感器
弦传感器=传感器=假;//构建参数到Web服务
字符串参数=输入+&放大器;+ +类型与&+传感器+&放大器;+键;// 输出格式
字符串输出=JSON;//构建URL到Web服务
字符串URL =https://maps.googleapis.com/maps/api/place/autocomplete/\"+output+\"?\"+ 参数;尝试{
    //撷取来自后台的Web服务数据
    数据= downloadUrl(URL);
}赶上(例外五){
    Log.d(后台任务,e.toString());
}
返回的数据;
} @覆盖
 保护无效onPostExecute(字符串结果){
super.onPostExecute(结果);//创建ParserTask
parserTask =新ParserTask();//开始解析由Web服务返回的JSON字符串
parserTask.execute(结果);
}
}
/ **一个类来分析JSON格式*的地方谷歌/
私有类ParserTask扩展的AsyncTask<字符串,整数,
清单<&HashMap的LT;字符串,字符串>>> { 的JSONObject jObject;@覆盖
保护列表与LT; HashMap的<字符串,字符串>> doInBackground(字符串...
jsonData){清单<&HashMap的LT;字符串,字符串>>地方= NULL;PlaceJSONParser placeJsonParser =新PlaceJSONParser();尝试{
    jObject =新的JSONObject(jsonData [0]);    //获取分析数据作为一个列表构造
    地方= placeJsonParser.parse(jObject);}赶上(例外五){
    Log.d(异常,e.toString());
}
回到地方;
}@覆盖
 保护无效onPostExecute(列表<&HashMap的LT;字符串,字符串>>的结果){    的String [] =由新的String [] {说明};
    INT []为= INT新[] {} android.R.id.text1;    //创建用于AutoCompleteTextView一个SimpleAdapter
    SimpleAdapter适配器=新SimpleAdapter(getBaseContext()
    结果,android.R.layout.simple_list_item_1,从,到);    atvPlaces.showDropDown();
        //设置适配器
        atvPlaces.setAdapter(适配器);        atvPlaces.setOnItemClickListener(新
        AdapterView.OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司,观景,INT
       位置,长的id){
                atvPlaces.dismissDropDown();
                字符串= search_bar.getText()的toString()。
                一个= a.substring(0,Math.min(则为a.length(),12));
                atvPlaces.setText(A +...);
            }
        });
}
}

下面是placejson code -

 公共类PlaceJSONParser {  / **
  *接收一个JSONObject并返回一个列表
  * /
 公开名单<&HashMap的LT;字符串,字符串>>解析(JSONObject的jObject){JSONArray jPlaces = NULL;
尝试{
    / **获取所有元素的'地方'数组中* /
    jPlaces = jObject.getJSONArray(predictions);
}赶上(JSONException E){
    e.printStackTrace();
}
/ **调用getPlaces和JSON对象的数组
 *每个JSON对象重新present的地方
 * /
返回getPlaces(jPlaces);
}
私人列表<&HashMap的LT;字符串,字符串>> getPlaces(JSONArray jPlaces){
INT placesCount = jPlaces.length();
清单<&HashMap的LT;字符串,字符串>> placesList =新的ArrayList<&HashMap的LT;弦乐,
串GT;>();
HashMap的<字符串,字符串>地方= NULL;/ **以每一个地方,解析并添加到列表对象* /
的for(int i = 0; I< placesCount;我++){
    尝试{
        / **调用getPlace与地方JSON对象解析地方* /
        地方= getPlace((JSONObject的)jPlaces.get(一));
        placesList.add(地方);    }赶上(JSONException E){
        e.printStackTrace();
    }
}返回placesList;
} / **
  *解析广场JSON对象
  * /
 私人的HashMap<字符串,字符串> getPlace(JSONObject的jPlace){HashMap的<字符串,字符串>地方=新的HashMap<字符串,字符串>();字符串ID =;
String引用=;
字符串描述=;尝试{    说明= jPlace.getString(说明);
    ID = jPlace.getString(ID);
    基准= jPlace.getString(参考);    place.put(说明,说明);
    place.put(_ ID,身份证);
    place.put(参考,参考);}赶上(JSONException E){
    e.printStackTrace();
}
 回到地方;
}
}


解决方案

尝试使用后(的Runnable r)的方法与AutoCompleteTextView是这样的:

  atvPlaces.post(新的Runnable(){
    公共无效的run(){
        atvPlaces.dismissDropDown();
    }
}

希望帮助!1

I am building an android application where I am using AutoComplete text to show the search of google place name.

Now the problem is I want to dismiss the list when I selected any item from the listview.

Here is my code -

!. oncreateview -

atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);

atvPlaces.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
    placesTask = new PlacesTask();
    placesTask.execute(s.toString());
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub
}

@Override
public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
}
});

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
    URL url = new URL(strUrl);

    // Creating an http connection to communicate with url
    urlConnection = (HttpURLConnection) url.openConnection();

    // Connecting to url
    urlConnection.connect();

    // Reading data from url
    iStream = urlConnection.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

    StringBuffer sb  = new StringBuffer();

    String line = "";
    while( ( line = br.readLine())  != null){
            sb.append(line);
    }

    data = sb.toString();

    br.close();

   }catch(Exception e){
    Log.d("Exception while downloading url", e.toString());
   }finally{
    iStream.close();
    urlConnection.disconnect();
   }
   return data;
   }

 // Fetches all places from GooglePlaces AutoComplete Web Service
 private class PlacesTask extends AsyncTask<String, Void, String>{

 @Override
 protected String doInBackground(String... place) {
// For storing data from web service
String data = "";

// Obtain browser key from https://code.google.com/apis/console
String key = "key";

String input="";



try {
    input = "input=" + URLEncoder.encode(place[0], "utf-8");
    input = input.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
}


// place type to be searched
String types = "types=geocode";

// Sensor enabled
String sensor = "sensor=false";

// Building the parameters to the web service
String parameters = input+"&"+types+"&"+sensor+"&"+key;

// Output format
String output = "json";

// Building the url to the web service
String url =

"https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+

 parameters;

try{
    // Fetching the data from web service in background
    data = downloadUrl(url);
}catch(Exception e){
    Log.d("Background Task",e.toString());
}
return data;
}

 @Override
 protected void onPostExecute(String result) {
super.onPostExecute(result);

// Creating ParserTask
parserTask = new ParserTask();

// Starting Parsing the JSON string returned by Web Service
parserTask.execute(result);
}
}


/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer,
List<HashMap<String,String>>>{

 JSONObject jObject;

@Override
protected List<HashMap<String, String>> doInBackground(String...
jsonData) {

List<HashMap<String, String>> places = null;

PlaceJSONParser placeJsonParser = new PlaceJSONParser();

try{
    jObject = new JSONObject(jsonData[0]);

    // Getting the parsed data as a List construct
    places = placeJsonParser.parse(jObject);

}catch(Exception e){
    Log.d("Exception",e.toString());
}
return places;
}

@Override
 protected void onPostExecute(List<HashMap<String, String>> result) {

    String[] from = new String[] { "description"};
    int[] to = new int[] { android.R.id.text1 };

    // Creating a SimpleAdapter for the AutoCompleteTextView
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
    result, android.R.layout.simple_list_item_1, from, to);

    atvPlaces.showDropDown();
        // Setting the adapter
        atvPlaces.setAdapter(adapter);

        atvPlaces.setOnItemClickListener(new
        AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int
       position, long id) {
                atvPlaces.dismissDropDown();
                String a = search_bar.getText().toString();
                a = a.substring(0, Math.min(a.length(), 12));
                atvPlaces.setText(a+"...");
            }
        });


}
}

Here is placejson code -

public class PlaceJSONParser {

  /**
  * Receives a JSONObject and returns a list
  */
 public List<HashMap<String, String>> parse(JSONObject jObject) {

JSONArray jPlaces = null;
try {
    /** Retrieves all the elements in the 'places' array */
    jPlaces = jObject.getJSONArray("predictions");
} catch (JSONException e) {
    e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
 * where each json object represent a place
 */
return getPlaces(jPlaces);
}


private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,
String>>();
HashMap<String, String> place = null;

/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
    try {
        /** Call getPlace with place JSON object to parse the place */
        place = getPlace((JSONObject) jPlaces.get(i));
        placesList.add(place);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

return placesList;
}

 /**
  * Parsing the Place JSON object
  */
 private HashMap<String, String> getPlace(JSONObject jPlace) {

HashMap<String, String> place = new HashMap<String, String>();

String id = "";
String reference = "";
String description = "";

try {

    description = jPlace.getString("description");
    id = jPlace.getString("id");
    reference = jPlace.getString("reference");

    place.put("description", description);
    place.put("_id", id);
    place.put("reference", reference);

} catch (JSONException e) {
    e.printStackTrace();
}
 return place;
}
}
解决方案

Try using post(Runnable r) method with the AutoCompleteTextView like this:

atvPlaces.post(new Runnable() {
    public void run() {
        atvPlaces.dismissDropDown();
    }
}

Hope that Helps!1

这篇关于如何simpleadapter列表视图中的Andr​​oid使用dismissDropDown()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:30