Norbis
Norbis

Reputation: 109

Multiple onClick events in Android Studio

So I've recently started working with Android Studio in hopes to learn some in depth Java/Android development. There are not too many decent tutorials/lessons around, but I managed to find quite a few. I got previous programming experience with C++/C# therefore grasping this was not THAT hard, but it does get confusing to the point where I am posting this question to which I could not find answer.

activity_main.xml

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add_button"
android:id="@+id/btnAddItem"
android:onClick="onAddItem"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />

So I've got my button set up there, and I already got an action assigned to it which basically upon click adds w/e the text was written next to it. NOW all I want to do is add a toast message each time it is clicked, but if I do it with setting up onClickListener it adds the item once, does not display the toast, then after trying to add another one it just displays the toast and does nothing else. (I can keep making the toast to re-appear).

The bit where I try to make the toast work a long with each "Add" button click is at public void onAddItem(View v)

MainActivity.java

   package com.example.norbis.webtutorial;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
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.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.PopupWindow;
import android.widget.Toast;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {

    ArrayList<String> items;
    ArrayAdapter<String> itemsAdapter;
    ListView lvItems;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvItems = (ListView) findViewById(R.id.lvItems);
        items = new ArrayList<String>();
        readItems();
        itemsAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items);
        lvItems.setAdapter(itemsAdapter);
        items.add("First item");
        items.add("Second Item");
        setupListViewListener();
    }

    private void setupListViewListener() {
        lvItems.setOnItemLongClickListener(
                new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> adapter,
                                                   View item, int pos, long id) {
                        items.remove(pos);
                        itemsAdapter.notifyDataSetChanged();
                        writeItems();
                        return true;
                    }
                });
    }

    public void onAddItem(View v) {
        EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
        String itemText = etNewItem.getText().toString();
        itemsAdapter.add(itemText);
        etNewItem.setText("");
        writeItems();
        //Basically this is the bit where I tried to add the listener.
        button = (Button)findViewById(R.id.btnAddItem);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Item added", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void readItems () {
        File filesDir = getFilesDir();
        File todoFile = new File(filesDir, "todo.txt");
        try {
            items = new ArrayList<String>(FileUtils.readLines(todoFile));
        } catch (IOException e) {
            items = new ArrayList<String>();
        }
    }

    public void writeItems() {
        File filesDir = getFilesDir();
        File todoFile = new File(filesDir, "todo.txt");
        try {
            FileUtils.writeLines(todoFile, items);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

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

I did not include the link to the tutorial it self as I've done it a while ago and so far only doing this for learning purposes, for which it was intended.

EDIT: This has now been answered and I just suck at over-complicating things. I would upvote you guys, but I do not have enough reputation just yet, thanks for helping me out.

Upvotes: 2

Views: 2103

Answers (3)

Bojan Kseneman
Bojan Kseneman

Reputation: 15668

onAddItem(View v) is your onClick event, so why are you setting another one? This basically is your onClick you usually see in the View.OnClickListener so don't set another one, instead just display the toast. By setting a new one, you have overridden your old one and all you have seen is the toast.

Toast.makeText(getApplicationContext(), "Item added", Toast.LENGTH_LONG).show();

Upvotes: 0

lean
lean

Reputation: 194

Because you changed the OnClickListener for the Button, this is permanent :)

Upvotes: 1

Karim
Karim

Reputation: 5308

Replace this in your code:

button = (Button)findViewById(R.id.btnAddItem);
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Item added", Toast.LENGTH_LONG).show();
            }
        });

with just:

Toast.makeText(getApplicationContext(), "Item added", Toast.LENGTH_LONG).show();

Reason: onAddItem(View) is already getting called each time you press on the button.

Upvotes: 1

Related Questions