Saturday, August 11, 2018

ListView with ArrayAdapter (Dynamic)

package net.samaysoftware.listviewdemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

import java.util.ArrayList;

public class CityListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    ListView lvCities;
    ArrayList<String> arr = new ArrayList<>();
    EditText etCityName;
    Button btnSave;
    ArrayAdapter<String> aa;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findAllViews();
        aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1,arr);
        lvCities.setAdapter(aa);
        lvCities.setOnItemClickListener(this);
        btnSave.setOnClickListener(this);
    }

    private void findAllViews() {
        lvCities = (ListView) findViewById(R.id.lvCities);
        etCityName = (EditText) findViewById(R.id.etCityName);
        btnSave = (Button)findViewById(R.id.btnSave);
    }

    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
        String selectedcity = arr.get(pos);
        Toast.makeText(this, "You clicked on position: "+selectedcity, Toast.LENGTH_SHORT).show();

        Intent i = new Intent(this, CityDetailActivity.class);
        i.putExtra("abcd",selectedcity);
        startActivity(i);
    }

    @Override    public void onClick(View view) {
        String name = etCityName.getText().toString();
        arr.add(name);
        aa.notifyDataSetChanged();
    }
}

No comments:

Post a Comment

Near by App

https://drive.google.com/file/d/0B2ag35s4X53Eb2pSQVI1SzNudE0/view