setText()错误,方法无法为TextView解析

时间:2018-10-26 09:23:06

标签: java android

此代码中的方法无法解析TextView
怎么了?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    EditText Username = (EditText) findViewById(R.id.EmployerNameEdit);

    String userName = Username.getText().toString();
    TextView changedName = (TextView) findViewById(R.id.employerName);
    changedName.setText(userName);

}

3 个答案:

答案 0 :(得分:0)

oncreate或创建全局edittext和TextView中的所有内容

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 EditText Username = (EditText) findViewById(R.id.EmployerNameEdit);

String userName = Username.getText().toString();
TextView changedName = (TextView) findViewById(R.id.employerName);
changedName.setText(userName);


 }

答案 1 :(得分:0)

据我所知,您想在Textview中设置Edittext的文本。为此必须使用任何按钮单击。否则,必须使用textChangeListener()方法。

按钮点击代码如下:

public class MainActivity extends AppCompatActivity {

EditText et;
TextView tv;
Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et=findViewById(R.id.et);
        tv=findViewById(R.id.tv);
        btn=findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text=et.getText().toString();
                tv.setText(text);
            }
        });
    }
}

答案 2 :(得分:0)

也许您错过了花括号,

公共类MainActivity扩展了AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText Username = (EditText) findViewById(R.id.EmployerNameEdit);

    String userName = Username.getText().toString();
    TextView changedName = (TextView) findViewById(R.id.employerName);
    changedName.setText(userName);
}

}

如果仍然遇到问题,请随意提问。 :)