简体   繁体   English

Android Studio中的多个onClick事件

[英]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. 因此,我最近开始使用Android Studio,希望能够深入学习Java / Android开发。 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. 我以前有使用C ++ / C#的编程经验,因此掌握这一点并不难,但是确实使我将这个问题发布到找不到答案的地步感到困惑。

activity_main.xml 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. 现在,我要做的就是每次单击都添加一条敬酒消息,但是如果我通过设置onClickListener来添加它,则它只会添加一次,不显示该敬酒,然后在尝试添加另一个消息后,它只会显示敬酒什么也没做。 (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) 每次单击“添加”按钮,我尝试使烤面包工作的时间较长,这是在public void onAddItem(View v)上进行的。

MainActivity.java 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. 我会赞成你们,但是我还没有足够的声誉,谢谢您的帮助。

因为您更改了按钮的OnClickListener,所以这是永久的:)

onAddItem(View v) is your onClick event, so why are you setting another one? onAddItem(View v)是您的onClick事件,那么为什么onAddItem(View v)设置另一个事件呢? This basically is your onClick you usually see in the View.OnClickListener so don't set another one, instead just display the toast. 这基本上是您通常在View.OnClickListener看到的onClick ,因此不要设置其他onClick ,而只是显示吐司。 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();

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. 原因:每次您按下按钮时, onAddItem(View)已经被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM