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

getText and setText function not working in android studio

我尝试在 android 工作室中使用 java 制作我的第一个转换器,但是 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);
            }
        });
    }
}

我希望我清楚 谢谢

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

中通过 id 检索它

试试这个-

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);
            }
        });
    }
}