Java 如何在列表中查找字符串<;文本视图>;安卓

Java 如何在列表中查找字符串<;文本视图>;安卓,java,android,Java,Android,我有一个TextView类型的“allPay”列表。我需要在这个列表中找到一个字符串,比如“abc”。我使用“contains()”从列表中查找字符串,但即使列表中包含此字符串,我也总是得到“false”作为答案 代码如下: TextView tv_method_name = (TextView) findViewById(R.id.tv_method_name); tv_method_name.setText("abc"); tv_method_name.setText("abcde");

我有一个TextView类型的“allPay”列表。我需要在这个列表中找到一个字符串,比如“abc”。我使用“contains()”从列表中查找字符串,但即使列表中包含此字符串,我也总是得到“false”作为答案

代码如下:

TextView tv_method_name = (TextView) findViewById(R.id.tv_method_name);
tv_method_name.setText("abc");
tv_method_name.setText("abcde");

List<TextView> allPay = new ArrayList<TextView>();

allpay.add(tv_method_name);
String str = "abc";
System.out.println("====allpay contains string?:" +     
allPay.contains("abc"));
TextView-tv\u-method\u-name=(TextView)findviewbyd(R.id.tv\u-method\u-name);
tv_method_name.setText(“abc”);
tv_method_name.setText(“abcde”);
List allPay=new ArrayList();
allpay.add(tv\u方法\u名称);
String str=“abc”;
System.out.println(“==allpay包含字符串?:”+
allPay.contains(“abc”);
结果:

===allpay包含字符串?:false

您不能执行此操作:

allPay.contains("abc"));
因为该方法包含正在搜索的对象。。。而不是对象的内容

因此,您询问TextView列表是否包含字符串。。这是不对的

您可以在循环中迭代列表并使用该方法进行搜索

List allPay=new ArrayList();
allpay.add(tv\u方法\u名称);
allpay.add(tv\u方法\u名称);
allpay.add(tv\u方法\u名称);
allpay.add(tv\u方法\u名称);
allpay.add(tv\u方法\u名称);
用于(TextView tv:allPay){
if(tv.getText.toString().indexOf(“abc”)!=-1){
System.out.println(“Found!!”;
}
}

为了检查文本,必须使用for循环或for each循环遍历文本视图列表。只需使用以下方法:

boolean listContains(List<TextView> txtViews, String textToCheck) {
    for (TextView txtView : txtViews) {
        if (txtView.getText().toString.contains(textToCheck)) {
            return true;
        }
    }
    return false;
}

我认为问题在于这一部分

TextView tv_method_name = (TextView) findViewById(R.id.tv_method_name);
tv_method_name.setText("abc");
tv_method_name.setText("abcde");

tv_method_名称修改了两次,因此变量中的最后一个值是“abcde”,当您查看值“abc”的列表时,该方法“Contains”返回“false”,因为该对象不存在。

您有一个TextView对象列表,并且正在搜索字符串。那不行

请尝试以下操作:

String yourText = "abc";
for(TextView tv: allPlay){
   if(tv!=null && tv.getText()!=null && tv.getText().toString().contains(yourText)){
       Log.d(TAG,"found:" + true);
   }
}

indexOf==any*abc*
,包含使用
indexOf
查看字符串类的方法本身。包含在对象地址而不是对象值的工作中,因此您需要创建一个帮助函数来循环并查找值感谢您的回答。解决了我的问题:)没问题。很高兴这有帮助。
TextView tv_method_name = (TextView) findViewById(R.id.tv_method_name);
tv_method_name.setText("abc");
tv_method_name.setText("abcde");
String yourText = "abc";
for(TextView tv: allPlay){
   if(tv!=null && tv.getText()!=null && tv.getText().toString().contains(yourText)){
       Log.d(TAG,"found:" + true);
   }
}