android-studio - getText 和 setText 函数在 android studio 中不起作用

我试图用 java 在 android studio 中制作我的第一个转换器,但是 setText 和 getText 两个函数不起作用

package com.example.unitconvertor;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity<editTextTextPersonName> extends AppCompatActivity {
    private Button button;
    private editTextTextPersonName editTextTextPersonName;
    private View editText;


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

        

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
                String s = editText.getText().toString();
                int inch = Integer.parseInt(s);
                double cm = 2.54 * inch;
                editText.setText( "the value is" + cm);
            }
        });
    }
}

我希望我清楚谢谢

回答1

尝试这个-

public class MainActivity extends AppCompatActivity  {
    private Button button;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        editText = findViewById(R.id.your_id);//ADD YOUR EDIT TEXT ID HERE


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
                String s = editText.getText().toString();
                int inch = Integer.parseInt(s);
                double cm = 2.54 * inch;
                editText.setText( "the value is" + cm);
            }
        });
    }
}

回答2

错误是你的“edittext”被声明为视图,像这样更正它: private EditText edittext; 然后,在你的 onCreate 方法 edittext = findViewById(R.id.your_id); 中通过 id 检索它

相似文章