在实现onClickListener时尝试获取Button文本

时间:2017-10-21 08:30:30

标签: java android onclick

我是android的新手,所以我希望我听起来不太吵闹。据说我制作了一个片段,专门为我的XML中的按钮实现OnclickListener。我需要默认的onclick函数才能保存按下的字符串文本但我无法弄清楚如何从视图中检索按钮的文本。这将帮助我为每个按钮制作一个if语句。有什么建议吗?

import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;

public class Section1Fragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "Section1Fragment";

    Button btnItem1;
    Button btnItem2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.section1,container,false);

        btnItem1 = (Button) view.findViewById(R.id.btnItem1);
        btnItem1.setOnClickListener(this);
        btnItem2 = (Button) view.findViewById(R.id.btnItem2);
        btnItem2.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View view) {
        if (view == btnItem1) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("button 1")
                    .setNegativeButton("Retry", null)
                    .create()
                    .show();
        }
        else if (view == btnItem2) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("button 2")
                    .setNegativeButton("Retry", null)
                    .create()
                    .show();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

view.getText()。toString()是您需要调用以获取视图的文本值的内容。这是示例代码。

 @Override
public void onClick(View view) {
    if (view == btnItem1) {
        Toast.makeText(getActivity(), btnItem1.getText().toString(), Toast.LENGTH_SHORT).show();

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("button 1")
                .setNegativeButton("Retry", null)
                .create()
                .show();
    }
    else if (view == btnItem2) {
        Toast.makeText(getActivity(), btnItem1.getText().toString(), Toast.LENGTH_SHORT).show();

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("button 2")
                .setNegativeButton("Retry", null)
                .create()
                .show();
    }
}

答案 1 :(得分:0)

首先,您要正确声明按钮,因此请进入xml文件,并确保按钮具有ID。您可以通过在按钮中执行以下操作来添加ID:android:id="@+id/button"

然后在Java代码文件中,您希望将其声明为:

final Button button = (Button) findViewById(R.id.button)

这应该有效,所以你想制作听众,这可以这样做:

button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View _v) {
    //what you want button to do
  }
});