如何在Listview中选择一个对象

时间:2017-06-15 08:55:27

标签: android listview

我有一个RemoteCar Control应用程序,在MainActivity页面上有一个按钮“location”,您可以单击该按钮以重定向到另一个活动(locationActivity)。在此活动中,我在Listview中显示JSON文件,现在我想点击这些对象来选择它们,并在主页面上显示类似于简单TextView的位置,没有什么特别之处。我怎么能这样做?

这是我的位置页面:

public class location extends AppCompatActivity {

    private String TAG = location.class.getSimpleName();
    private ListView lv;

    ArrayList<HashMap<String, String>> locationList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);

        locationList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(location.this, "Json Data is downloading", Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            // Making a request to url and getting response
            String url = "url";
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    //JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    //JSONArray locations = jsonObj.getJSONArray("");
                    JSONArray locations_ = new JSONArray(jsonStr);


                    // looping through All Contacts
                    for (int i = 0; i < locations_.length(); i++) {
                        JSONObject c = locations_.getJSONObject(i);
                        String type = c.getString("type");
                        String name = c.getString("name");
                        String address = c.getString("address");
                        String lat = c.getString("lat");
                        String lon = c.getString("lon");
                        String icon;
                        if(c.has("icon")){
                            //your json is having "icon" Key, get the value
                            icon = c.getString("icon");
                        }
                        else{
                            //your json is NOT having "icon" Key,  assign a dummy value
                            icon = "/default/icon_url()";
                        }

                        // tmp hash map for single contact
                        HashMap<String, String> location = new HashMap<>();

                        // adding each child node to HashMap key => value
                        location.put("type", type);
                        location.put("name", name);
                        location.put("address", address );
                        location.put("lat", lat);
                        location.put("lon", lon);
                        location.put("icon", icon);

                        // adding contact to contact list
                        locationList.add(location);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(location.this, locationList,
                    R.layout.list_item, new String[]{"type", "name", "address", "lat", "lon", "icon"},
                    new int[]{R.id.type, R.id.name, R.id.address, R.id.lat, R.id.lon, R.id.icon});
            lv.setAdapter(adapter);
        }
    }

这是我的MainActivity页面

public class MainActivity extends AppCompatActivity {
    public ProgressBar fuelBar;
    public Button lockButton;
    public Button engButton;
    public Button refuelButton;
    public Button locationButton;
    public SeekBar seekBarButton;
    public TextView seekText;
    int incFuel = 0;
    final String FUELBAR = "fuelBar";
    final String AC_BARTEXT = "acBarText";
    final String AC_BAR = "acBar";
    final String REFUELBUTTON = "refuelButton";
    final String STARTENGINE = "startEngineButton";

    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locationButton = (Button) findViewById(R.id.locationB);
        lockButton = (Button) findViewById(R.id.lockB);
        engButton = (Button) findViewById(R.id.engB);
        refuelButton = (Button) findViewById(R.id.refuelB);
        fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
        fuelBar.setMax(100);
        fuelBar.setProgress(30);
        refuelButton.setText(R.string.refuelB);
        lockButton.setText(R.string.lockB);
        locationButton.setText(R.string.locationB);
        engButton.setText(R.string.engB);
        seekBarButton = (SeekBar) findViewById(R.id.seekBar);
        seekText = (TextView) findViewById(R.id.seekText);

        sharedPref = getPreferences(Context.MODE_PRIVATE);
        editor = sharedPref.edit();

        seek_bar();
        lockPage();
        locationPage();
    }
    @Override
    protected void onPause(){
        super.onPause();
        editor.putInt(FUELBAR, fuelBar.getProgress());
        editor.commit();

        String tmpAC = "AC : " + String.valueOf(seekBarButton.getProgress()+18) + "°";
        editor.putString(AC_BARTEXT, tmpAC);
        editor.commit();

        editor.putInt(AC_BAR, seekBarButton.getProgress());
        editor.commit();

        editor.putString(REFUELBUTTON, refuelButton.getText().toString());
        editor.commit();

        editor.putString(STARTENGINE, engButton.getText().toString());
        editor.commit();

    }
    @Override
    public void onResume(){
        super.onResume();
        fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
        incFuel = sharedPref.getInt(FUELBAR, 0);
        fuelBar.setProgress(incFuel);

        seekText = (TextView) findViewById(R.id.seekText);
        String tmpAC = sharedPref.getString(AC_BARTEXT, "error");
        seekText.setText(tmpAC);

        seekBarButton = (SeekBar) findViewById(R.id.seekBar);
        int tmpInt = sharedPref.getInt(AC_BAR, 18);
        seekBarButton.setProgress(tmpInt);

        tmpAC = sharedPref.getString(REFUELBUTTON, "REFUEL");
        refuelButton.setText(tmpAC);

        tmpAC = sharedPref.getString(STARTENGINE, "START ENGINE");
        engButton.setText(tmpAC);

    }

    @Override
    public void onStop(){
        super.onStop();
    }


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.engB:
                if (engButton.getText() == "ENGINE RUNNING") {
                    engButton.setText("START ENGINE");
                } else {
                    if (fuelBar.getProgress() > 0) {
                        Toast.makeText(MainActivity.this, "starting engine..", Toast.LENGTH_SHORT).show();
                        engButton.setText("ENGINE RUNNING");
                        if (fuelBar.getProgress() >= 10) {
                            incFuel = fuelBar.getProgress();
                            incFuel -= 10;
                            fuelBar.setProgress(incFuel);
                            if (fuelBar.getProgress() < 100)
                                refuelButton.setText("REFUEL");
                        }
                    } else if (fuelBar.getProgress() == 0) {
                        Toast.makeText(MainActivity.this, "no fuel", Toast.LENGTH_SHORT).show();
                        engButton.setText("EMPTY GASTANK");
                    } else
                        engButton.setText("START ENGINE");
                }
                break;
            case R.id.refuelB:
                if (fuelBar.getProgress() == 0) {
                    engButton.setText("START ENGINE");
                    incFuel = fuelBar.getProgress();
                    incFuel += 10;
                    fuelBar.setProgress(incFuel);
                } else if (fuelBar.getProgress() < 100) {
                    incFuel = fuelBar.getProgress();
                    incFuel += 10;
                    fuelBar.setProgress(incFuel);
                } else {
                    Toast.makeText(MainActivity.this, "tank is full", Toast.LENGTH_SHORT).show();
                    refuelButton.setText("FULL");
                }
                break;
        }
    }

        public void seek_bar() {
        seekBarButton = (SeekBar) findViewById(R.id.seekBar);
        seekText = (TextView) findViewById(R.id.seekText);
        seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
        seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progressNum;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progressNum = progress;
                seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
            }
        });
    }


    public void lockPage() {
        lockButton = (Button) findViewById(R.id.lockB);
        lockButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
                startActivity(lockPage);
            }
        });
    }

    public void locationPage() {
        locationButton = (Button) findViewById(R.id.locationB);
        locationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent locationPage = new Intent(MainActivity.this, location.class);
                startActivity(locationPage);
            }
        });
    }
}

对于代码墙我很难不确定要提供多少信息。

1 个答案:

答案 0 :(得分:0)

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(MyActivity.this, "location:" + " "+ stringList[position] + " " + "hauptbahnhof selected", Toast.LENGTH_SHORT).show();
        }
    });

define your list of string as private out of onCreate