str.length()不能像我认为的那样工作

时间:2014-03-13 23:04:03

标签: android string

当我进入" AA"进入我的2个TextViews时,它永远不会移动到我的其他活动当" AA" .length()应该是2,使它切换到我的其他活动,但它永远不会。然后我检查了它的打印输出是什么,它打印98和94作为2个字符串的长度应该是2 2有什么建议吗?

public class DataEntry extends Activity {
String parent1 = "";
String parent2 = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_data_entry);
    Button calc = (Button)findViewById(R.id.btnCalc);

    calc.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            TextView tv = (TextView)findViewById(R.id.txtFirstParent);
            TextView tv1 = (TextView)findViewById(R.id.txtParent2);
            String str = tv.toString().trim();
            String str2 = tv1.toString().trim();
            parent1 = str;
            parent2 = str2;
            if(str.length()==2 && str2.length()==2){
                Intent otherIntent = new Intent(DataEntry.this, MonoHybrid.class);
                otherIntent.putExtra("parent1",parent1);
                otherIntent.putExtra("parent2",parent2);
                startActivity(otherIntent);
            }
            else if(str.length()==4 && str2.length()==4){
                Intent otherIntent = new Intent(DataEntry.this, DiHybrid.class);
                otherIntent.putExtra("parent1",parent1);
                otherIntent.putExtra("parent2",parent2);
                startActivity(otherIntent);
            }
            else if(str.length()==6 && str2.length()==6){
                Intent otherIntent = new Intent(DataEntry.this, TriHybrid.class);
                otherIntent.putExtra("parent1",parent1);
                otherIntent.putExtra("parent2",parent2);
                startActivity(otherIntent);
            }
            else
                tv.setText(str.length() +" "+ str2.length());
                tv1.setText(str.length() + " " + str2.length());
                //tv.setText("Error please enter a MonoHybrid \"AA\" DiHybrid \"AABB\" or TriHybrid \"AABBCC\"");
                //tv1.setText("Error please enter a MonoHybrid \"AA\" DiHybrid \"AABB\" or TriHybrid \"AABBCC\"");
        }
    });
}

}

2 个答案:

答案 0 :(得分:2)

String str = tv.getText().toString().trim();

代替。

答案 1 :(得分:0)

我认为您没有正确地从TextView获取文本。

尝试

String str = tv.getText().toString();
String str2 = tv1.getText().toString();

TextView.toString()返回对象的可读描述,而不是输入的实际文本(来自API documentation)。

相关问题