-1

I am new on Stack Overflow and i read this Thread ( ListView with Add and Delete Buttons in each Row in android ) and i implemented the Answer ( https://stackoverflow.com/a/23021960/7262380 ) in my code. All works fine. But now i want that if i click on a List View Item that anything happen what i have to do?

My actual Code (list Adapter)

package de.control;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class listAdapter extends BaseAdapter implements ListAdapter {

    //Create Variables

    private ArrayList<String> list = new ArrayList<String>();
    private ArrayList<Sort> aktuelleObjektListe = new ArrayList<>();
    private Context context;
    public static DBHelper dataSource;
    TextView quantity = null;
    public static final String LOG_TAG = listAdapter.class.getSimpleName();

    //Finished

    //Create ListAdapter

    public listAdapter(ArrayList<String> list, Context context) {
        this.list = list;
        this.context = context;
        dataSource = new DBHelper(context);
        dataSource.open();
        aktuelleObjektListe = dataSource.getAllSorts();
        dataSource.close();
    }

    //Finished

    //Unused but required

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int pos) {
        return list.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return 0;
        //just return 0 if your list items do not have an Id variable.
    }

    //Finished

    //Update ListView ( is Called by "adapter.notifyDataSetChanged();" )

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

        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listlayout, null);

        }

        TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
        listItemText.setText(list.get(position));

        quantity = (TextView)view.findViewById(R.id.quantity_double);
        quantity.setText( Integer.toString(  aktuelleObjektListe.get(position).getQuantity()  ) );

     //Finished

        //Handle ADD and DELETE Button

        Button add1toSort = (Button)view.findViewById(R.id.add1toSort);
        Button remove1fromSort = (Button)view.findViewById(R.id.remove1fromSort);

    add1toSort.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            dataSource.open();

            Sort sort = dataSource.getAllSorts().get(position);

            dataSource.updateSortInDB(sort.getId(), sort.getSort(), (sort.getQuantity() + 1) );

            aktuelleObjektListe = dataSource.getAllSorts();

            dataSource.close();

            notifyDataSetChanged();
        }
    });

    remove1fromSort.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            dataSource.open();

            Sort sort = dataSource.getAllSorts().get(position);

            dataSource.updateSortInDB(sort.getId(), sort.getSort(), (sort.getQuantity() - 1) );

            aktuelleObjektListe = dataSource.getAllSorts();

            dataSource.close();

            notifyDataSetChanged();
        }
    });

    //Finished
    return view;
}

}

My actual Code (MainActivity)

package de.control;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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.ListView;

import java.util.ArrayList;

public class overview extends AppCompatActivity {

    //Create Variable

    public static DBHelper dataSource;
    public static final String LOG_TAG = overview.class.getSimpleName();
    public static final String tmp = "Test";

    ListView possessionList;
    Button addSort;

    listAdapter adapter;
    public ArrayList<String> listItems;
    public static ArrayList<Sort> Objects;

    //Finished

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

        // Create ListView (ID: possessionList)

        dataSource = new DBHelper(this);
        dataSource.open();
        Objects = dataSource.getAllSorts();

        possessionList = (ListView)findViewById(R.id.overview_possessionList);
        listItems = new ArrayList<String>();

        adapter = new listAdapter(listItems, this);
        possessionList.setAdapter(adapter);

        Log.d(LOG_TAG, "Die Datenquelle wird geöffnet.");

        Log.d(LOG_TAG, "ListView wird Aktuelisiert");
        updateList();

        Log.d(LOG_TAG, "Die Datenquelle wird geschlossen.");
        dataSource.close();

        //Finished

        // Handle what happend by Pressing a List Item (DOESENT WORK)

         possessionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.d(LOG_TAG, "Test");
            }
        });

        //Finished

        // Switch Label on Button (ID: addSort)

        addSort = (Button)findViewById(R.id.overview_completeAddition);
        final Intent addIntent = new Intent(overview.this,addsort.class);

        addSort.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                startActivity(addIntent);
            }
        });

        //Finished
    }

    // Add all Objekts to the ListView

    public boolean updateList()
    {
        try {
            listItems.clear();

            Objects = dataSource.getAllSorts();

            for (int i = 0; i < Objects.size(); i++) {
                listItems.add(Objects.get(i).getSort());
            }

            adapter.notifyDataSetChanged();

            return true;
        }
        catch (Exception ex){
            return false;
        }
    }

    //Finished

    //Add the Menü

    @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);
    }

    //Finished

}
xBarkeeper
  • 47
  • 6

5 Answers5

5

How can i add a setOnClickListener to my ListView Android

You should implement setOnItemClickListener to your possessionList listView

possessionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // your code
    }
});

Another alternative would be add android:descendantFocusability="blocksDescendants" in the LinearLayout or RelativeLayout, not inside listView element.

Example

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            .....
    android:descendantFocusability="blocksDescendants"
    tools:context="de.control.overview"> 
John Joe
  • 12,412
  • 16
  • 70
  • 135
0
possessionList.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

        Log.i("Hello!", "Y u no see me?");

    }
});

from ListView with OnItemClickListener android

0

It would be better for you to use recyclerview instead of listView.

// Item Click Listener for the listview
 OnItemClickListener itemClickListener = new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View container, int 
                                     position, long id) {
                // Getting the Container Layout of the ListView
                LinearLayout linearLayoutParent = (LinearLayout) container;

                // Getting the inner Linear Layout
                LinearLayout linearLayoutChild = (LinearLayout ) 
                 linearLayoutParent.getChildAt(1);

                // Getting the Country TextView
                TextView tvCountry = (TextView) linearLayoutChild.getChildAt(0);

                Toast.makeText(getBaseContext(), tvCountry.getText().toString(), 
                 Toast.LENGTH_SHORT).show();
            }
        };

        // Setting the item click listener for the listview
        listView.setOnItemClickListener(itemClickListener);
John Joe
  • 12,412
  • 16
  • 70
  • 135
Nouman Ch
  • 4,023
  • 4
  • 29
  • 42
0

For example, If I have a list view like this:

ListView mListView = (ListView) mLayout.findViewById(R.id.my_list_view);

You can use setOnItemClickListener for click on each item in your list view event:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //Do what you want to each item here
    }
});

Example with more details: https://www.androidhive.info/2011/10/android-listview-tutorial/

BlakeR
  • 33
  • 6
0

Try adding android:focusable="false" to your text views and buttons in your listlayout.xml elements and add this line android:descendantFocusability="blocksDescendants" in list layout's parent layout.

John Joe
  • 12,412
  • 16
  • 70
  • 135
MinnuKaAnae
  • 1,646
  • 3
  • 23
  • 35