Android ListView不选择行

时间:2017-05-16 00:04:25

标签: android listview listviewitem

我正在尝试使用ListView,我想选择每一行来启动不同的活动,但OnItemSelectedItem方法在OnCreate的内部和外部都不起作用。

这是代码。

MainActivity:

package com.example.dos_6.app_chef.Activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dos_6.app_chef.Adapters.MenuAdapter;
import com.example.dos_6.app_chef.Clases.Facultad;
import com.example.dos_6.app_chef.Clases.Menu;
import com.example.dos_6.app_chef.Clases.Pais;
import com.example.dos_6.app_chef.Clases.Universidad;
import com.example.dos_6.app_chef.R;
import com.example.dos_6.app_chef.Util.Util;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.dos_6.app_chef.Util.Constantes.SERVER_GETFACULTAD_ID_UNI;
import static com.example.dos_6.app_chef.Util.Constantes.SERVER_GETMENU;
import static com.example.dos_6.app_chef.Util.Constantes.SERVER_GETMENU_DIA;
import static com.example.dos_6.app_chef.Util.Constantes.SERVER_GETMENU_ID_FACULTAD;
import static com.example.dos_6.app_chef.Util.Constantes.SERVER_GETPAIS;
import static com.example.dos_6.app_chef.Util.Constantes.SERVER_GETUNIVERSIDAD;
import static com.example.dos_6.app_chef.Util.Constantes.SERVER_URL;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, AdapterView.OnItemClickListener {

    private Intent intent = null;

    private Spinner spinner_universidad = null;
    private Spinner spinner_facultad = null;
    private Spinner spinner_dias = null;

    private ListView lvMenu = null;

    private ListView lvPlatos = null;

    private TextView tv_primer = null;
    private TextView tv_segundo = null;
    private TextView tv_postre = null;
    private TextView tv_bebida = null;

    private Universidad universidad = null;

    private List<Universidad> listaUniversidad = null;
    private List<Facultad> listaFacultad = null;
    private List<Pais> listaPais = null;
    private List<Menu> listaMenu = null;
    private List<Menu> listaPlatos = null;

    private MenuAdapter menuAdapter = null;
    private MenuAdapter platoAdapter = null;

    private WebServiceMenu webServiceMenu = null;

    //TODO nº Semana

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        listaUniversidad = new ArrayList<>();
        listaFacultad = new ArrayList<>();
        listaPais = new ArrayList<>();
        listaPlatos = new ArrayList<>();

        spinner_universidad = (Spinner) findViewById(R.id.main_spin_lista_uni);
        spinner_dias = (Spinner) findViewById(R.id.main_spinner_dias);
        //ListView start
        lvPlatos = (ListView) findViewById(R.id.main_lv_platos);
        lvPlatos.setOnItemClickListener(this);
        String[] ps = this.getResources().getStringArray(R.array.platos_array);
        Menu m;
        for(int i = 0 ; i < ps.length; i++){
            m = new Menu();
            m.setNombre_plato(ps[i]);
            getListaPlatos().add(m);
        }
        platoAdapter = new MenuAdapter(this, R.layout.menu_item, getListaPlatos());
        lvPlatos.setAdapter(platoAdapter);
        //ListView End
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

            WebService webService = new WebService();
            webService.execute();

        listaMenu = new ArrayList<>();

        universidad = new Universidad();
        universidad.setId(0);
        universidad.setNombre(getString(R.string.reg_spinner_pos0_universidad));
        getListaUniversidad().add(0,universidad);
        ArrayAdapter<Universidad> universidadArrayAdapter = new ArrayAdapter<Universidad>(this,
                R.layout.support_simple_spinner_dropdown_item, getListaUniversidad());
        spinner_universidad.getDropDownHorizontalOffset();
        spinner_universidad.setAdapter(universidadArrayAdapter);
        spinner_universidad.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getListaFacultad().clear();
                String uni = spinner_universidad.getItemAtPosition(spinner_universidad.getSelectedItemPosition()).toString();
                seleccionarFacultad(uni);
                ArrayAdapter<Facultad> arrayAdapter = new ArrayAdapter<Facultad>(getBaseContext(), R.layout.support_simple_spinner_dropdown_item, getListaFacultad());
                spinner_facultad = (Spinner) findViewById(R.id.main_spin_lista_fac);
                spinner_facultad.getDropDownHorizontalOffset();
                spinner_facultad.setAdapter(arrayAdapter);
                spinner_facultad.getOnItemSelectedListener();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        ArrayAdapter<String> diasAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, fillDias());
        spinner_dias.getDropDownHorizontalOffset();
        spinner_dias.setAdapter(diasAdapter);
        spinner_dias.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    Facultad facultad = (Facultad) spinner_facultad.getItemAtPosition(spinner_facultad.getSelectedItemPosition());
                    String dia = spinner_dias.getItemAtPosition(spinner_dias.getSelectedItemPosition()).toString();

                    if(spinner_dias.getSelectedItem().equals(spinner_dias.getItemAtPosition(0))){
                        return;
                    }else {
                        mostrarMenu(dia, String.valueOf(facultad.getId()));
                    }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                return;
            }
        });

    }

    public void seleccionarFacultad(String uni) {
        if (spinner_universidad.getSelectedItem().equals(spinner_universidad.getItemAtPosition(0))) {
            Facultad facultad = new Facultad();
            facultad.setNombre(getString(R.string.reg_spinner_pos0_facultad));
            getListaFacultad().add(facultad);
        } else {
            for(Universidad universidad : getListaUniversidad()){
                if(universidad.getNombre().equals(uni)){
                    Facultad facultad = new Facultad();
                    facultad.setNombre(getString(R.string.reg_spinner_posX_facultad));
                    getListaFacultad().add(0,facultad);
                    WebServiceFacultad  webServiceFacultad = new WebServiceFacultad();
                    webServiceFacultad.execute(String.valueOf(universidad.getId()));

                }
            }
        }
    }

    public void mostrarMenu(String dia, String id_facultad){
        WebServiceMenu webServiceMenu = new WebServiceMenu();
        webServiceMenu.execute(dia,id_facultad);

        //menuAdapter = new MenuAdapter(this, R.layout.menu_item, getListaMenu());
        //lvMenu.setAdapter(menuAdapter);
    }

    public ArrayList<String> fillDias(){
        ArrayList<String> dias = null;

        dias = new ArrayList<>();
        dias.add(getString(R.string.weekday)+" "+Util.numerWeekOfYear());
        //dias.add(getString(R.string.dia_pos0));
        dias.add(getString(R.string.main_bt_lunes));
        dias.add(getString(R.string.main_bt_martes));
        dias.add(getString(R.string.main_bt_miercoles));
        dias.add(getString(R.string.main_bt_jueves));
        dias.add(getString(R.string.main_bt_viernes));
        return dias;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            /*case R.id.main_tv_primer_plato:
                intent = new Intent(this, Platos_Activity.class);
                intent.putExtra("orden","1");
                intent.putExtra("lista_menu",(Serializable) getListaMenu());
                startActivity(intent);
                break;
            case R.id.main_tv_seg_plato:
                intent = new Intent(this, Platos_Activity.class);
                intent.putExtra("orden","2");
                intent.putExtra("lista_menu",(Serializable) getListaMenu());
                startActivity(intent);
                break;
            case R.id.main_tv_postre:
                intent = new Intent(this, Platos_Activity.class);
                intent.putExtra("orden","3");
                intent.putExtra("lista_menu",(Serializable) getListaMenu());
                startActivity(intent);
                break;
            case R.id.main_tv_bebida:
                intent = new Intent(this, Platos_Activity.class);
                intent.putExtra("orden","4");
                Menu menu = null;
                List<Menu> menuList = new ArrayList<>();
                getListaMenu().clear();
                String[] bebidas = new String[]{"Agua","Refresco","Cerveza"};
                for(int i = 0 ; i < 3;i++){
                    menu = new Menu();
                    menu.setOrden_plato("4");
                    menu.setNombre_plato(bebidas[i]);
                    getListaMenu().add(menu);
                }
                intent.putExtra("lista_menu",(Serializable) getListaMenu());
                startActivity(intent);
                break;*/
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(position == ListView.INVALID_POSITION){
            return;
        }
        Menu menu = getListaPlatos().get(position);
        Intent intent;
        if(menu.getNombre_plato().equalsIgnoreCase(getString(R.string.primer_plato))) {
            intent = new Intent(this, Platos_Activity.class);
            intent.putExtra("orden","1");
            intent.putExtra("lista_menu",(Serializable) getListaMenu());
            startActivity(intent);
        }else if(menu.getNombre_plato().equalsIgnoreCase(getString(R.string.segundo_plato))){
            intent = new Intent(this, Platos_Activity.class);
            intent.putExtra("orden","2");
            intent.putExtra("lista_menu",(Serializable) getListaMenu());
            startActivity(intent);
        }else if(menu.getNombre_plato().equalsIgnoreCase(getString(R.string.postre))){
            intent = new Intent(this, Platos_Activity.class);
            intent.putExtra("orden","3");
            intent.putExtra("lista_menu",(Serializable) getListaMenu());
            startActivity(intent);
        }else{
            intent = new Intent(this, Platos_Activity.class);
            intent.putExtra("orden","4");
            Menu refrescos = null;
            getListaMenu().clear();
            String[] bebidas = this.getResources().getStringArray(R.array.bebidas_array);
            for(int i = 0 ; i < 3;i++){
                refrescos = new Menu();
                refrescos.setOrden_plato("4");
                refrescos.setNombre_plato(bebidas[i]);
                getListaMenu().add(refrescos);
            }
            intent.putExtra("lista_menu",(Serializable) getListaMenu());
            startActivity(intent);
        }
        Toast.makeText(this, menu.getNombre_plato(), Toast.LENGTH_LONG).show();
    }

    private class WebService extends AsyncTask<String, Void, Void>{

        private ProgressDialog dialog;

        @Override
        protected Void doInBackground(String... params) {


            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            Universidad[] universidadArray=null;

            try{
                universidadArray = restTemplate.getForObject(SERVER_URL + SERVER_GETUNIVERSIDAD, Universidad[].class);
            }catch (Exception e){

            }

            for(Universidad universidad : universidadArray){
                getListaUniversidad().add(universidad);
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            dialog = new ProgressDialog(MainActivity.this);
            dialog.setTitle(R.string.mensaje_cargando);
            dialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            if (dialog != null)
                dialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
         }
    }

    private class WebServicePais extends AsyncTask<String, Void, Void>{

        private ProgressDialog dialog;

        @Override
        protected Void doInBackground(String... params) {


            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            Pais[] paisArray = restTemplate.getForObject(SERVER_URL+SERVER_GETPAIS, Pais[].class);
            getListaPais().addAll(Arrays.asList(paisArray));
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //spinner_universidad.setAdapter(null);

            /*dialog = new ProgressDialog(MainActivity.this);
            dialog.setTitle(R.string.mensaje_cargando);
            dialog.show();*/
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            if (dialog != null)
                dialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }

    private class WebServiceFacultad extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... params) {
            int id_uni = Integer.parseInt(params[0]);
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            Facultad[] facultadArray = restTemplate.getForObject(SERVER_URL + SERVER_GETFACULTAD_ID_UNI+id_uni, Facultad[].class);
            getListaFacultad().addAll(Arrays.asList(facultadArray));
            return null;
        }
    }

    private class WebServiceMenu extends AsyncTask<String, Void, Void>{

        private ProgressDialog dialog;

        @Override
        protected Void doInBackground(String... params) {
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            Menu[] menu = restTemplate.getForObject(SERVER_URL+SERVER_GETMENU+SERVER_GETMENU_DIA+params[0]
                    +SERVER_GETMENU_ID_FACULTAD+Integer.parseInt(params[1]), Menu[].class);
            getListaMenu().addAll(Arrays.asList(menu));
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            getListaMenu().clear();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setTitle(R.string.mensaje_cargando);
            dialog.show();
        }


        protected void onPostExecute(Void aVoid) {
            if (dialog != null)
                dialog.dismiss();

            //menuAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            //menuAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

       if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public List<Universidad> getListaUniversidad() {
        return listaUniversidad;
    }

    public void setListaUniversidad(List<Universidad> listaUniversidad) {
        this.listaUniversidad = listaUniversidad;
    }

    public List<Pais> getListaPais() {
        return listaPais;
    }

    public void setListaPais(List<Pais> listaPais) {
        this.listaPais = listaPais;
    }

    public List<Facultad> getListaFacultad() {
        return listaFacultad;
    }

    public void setListaFacultad(List<Facultad> listaFacultad) {
        this.listaFacultad = listaFacultad;
    }

    public List<Menu> getListaMenu() {
        return listaMenu;
    }

    public void setListaMenu(List<Menu> listaMenu) {
        this.listaMenu = listaMenu;
    }

    public List<Menu> getListaPlatos() {
        return listaPlatos;
    }

    public void setListaPlatos(List<Menu> listaPlatos) {
        this.listaPlatos = listaPlatos;
    }
}

每一行都使用这个XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/menu_item_imv"
        android:layout_width="118dp"
        android:layout_height="80dp"
        android:focusable="false"/>

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Switch" />

    <LinearLayout
        android:layout_width="270dp"
        android:layout_height="80dp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/menuitem_tv_nombre_plato"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TextView"
            android:textAlignment="center"
            android:textColor="@color/colorPrimaryDark"
            />

    </LinearLayout>

</LinearLayout> 

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

使用单击适配器内部。类似的原因我不知道你的适配器类我从我的代码粘贴。

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

  if (convertView == null) {
          LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
          convertView = mInflater.inflate(R.layout.item_card_list, null);
      }



  convertView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

    }
  });

  convertView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {

      return true;
    }
  });



      return convertView;
}

答案 1 :(得分:0)

TL; DR我的直觉反应将是重叠的听众(我在一个活动中计算了6个单独的监听器调用)。将Log.e事件放在每个侦听器中,单击要单击的内容并查看Log.e触发的内容。你会知道正在调用什么是Listener(换句话说,哪个Listener正在吞噬你点击事件)。

如果没有被解雇,你很可能没有正确实现你的听众。

答案 2 :(得分:0)

如果您创建自定义适配器会很好。

尝试以下链接: -

http://www.journaldev.com/10416/android-listview-with-custom-adapter-example-tutorial