简体   繁体   English

我怎么知道点击了哪个“TextView”

[英]How could I know which “TextView” is clicked

I was creating a dynamic Text View and I need to know which one of those Text views was clicked by the user i read that i need to use getTag() method but it keeps return null when i try it this is my activity code in java:我正在创建一个动态文本视图,我需要知道其中一个文本视图被用户单击,我读到我需要使用 getTag() 方法,但是当我尝试它时它一直返回 null 这是我在 java 中的活动代码:

        for(int i=0;i<size;i++){
        TextView temp = new TextView(this);
        temp.setId(i);
        temp.setId(i);
        String s = "";
        temp.setText(s);
        temp.setTextColor(Color.RED);
        mylieniarlayout.addView(temp);
        tv[i] = temp;
    }
    final TextView answertv = findViewById(R.id.answertv);
    mylieniarlayout.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(),"ID: "+ v.getTag(), Toast.LENGTH_SHORT).show();
            answertv.setText("Clicked ID: " + v.getTag());
        }
    });

You can try if else condition你可以试试if else条件

Like:喜欢:

if(v.getTag() == 0){
  //Show position 0 here
} else {
  //Other position
}

Hope you got your answer希望你得到你的答案

Firstly, setTag() and getTag() methods on view are not used for identifying the view.首先,视图上的 setTag() 和 getTag() 方法不用于识别视图。 We use getId() for identifying the view.我们使用 getId() 来识别视图。 Please read document here, getTag on android developers请在此处阅读文档, 在 android 开发人员上获取标签

Secondly, your onClickListner is on layout which won't give you the selected id of textView.其次,您的 onClickListner 在布局上,不会为您提供 textView 的选定 ID。 In your code you are setting an ID for the text view and trying to fetch a tag which is a mistake.在您的代码中,您正在为文本视图设置一个 ID 并尝试获取一个错误的标签。

  1. onClickListener should be on the textview of which you want a tag. onClickListener 应该在您想要标签的 textview 上。
  2. While creating a textView set the tag and then you will get the tag for that textview.在创建 textView 时设置标签,然后您将获得该 textview 的标签。

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

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