简体   繁体   中英

Can we create new class in MainActivity.java?

How to add another class within this class MainActivity extends AppCompatActivity. If there was this line of code,

public class MainActivity extends AppCompatActivity {
    private EditText Num1;
    private Button btnAdd;

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

        Num1 = (EditText) findViewById(R.id.firstName);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(new View.OnClickListener(){
        @Override
            public void onClick(View v) {
                multiLine.setText(Num1.getText().toString()
       });
    }
}

can there be another class where I can call the Num1 value, if so how to pass the EditText value on this new Calculate class. I'm new to Android Studio plus the java so I would appreciate any ideas you have.

public class Calculate {
    private int num = Num1

}

I'm not sure if my question makes sense but I've been trying to pass the Num1 value to the new class I have created. I could be doing it wrong and also I tried creating new class in java but didn't know how to call the values there from MainActivity.java.

You can put any number of classes in a single .java file, even as peers not inner classes. That is typically not done though. It's standard to put each new class in a new .java file.

just put the calculate class above the lowest bottom bracket like this:

public class MainActivity extends AppCompatActivity {
    private EditText Num1;
    private Button btnAdd;

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

        Num1 = (EditText) findViewById(R.id.firstName);
        btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(new View.OnClickListener(){
        @Override
            public void onClick(View v) {
                multiLine.setText(Num1.getText().toString()
       });
    }
    public class Calculate {
        private int num;

        public Calculate(int number){
            num = number
        }
    }
}

You can pass the Num1-value via the constructor (or you decide to write a setter-method for it). Use it in the MainActivity like this:
Calculate calc = new Calculate(Num1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM