我在Eclipse中使用控制台和Linux中的终端窗口编写了一个程序。我现在正在将它转换为Android应用程序,我已经完成了Android UI的基本功能,直到它需要使用我编写的程序的Java文件中的逻辑。我在Java文件中的所有输入都来自键盘(来自扫描仪)。
我的问题是:我如何对其进行转换以使其与应用的用户交互一起工作?
唯一的输入来自内置NumberPicker
。 Java文件从main方法开始:public static void main(String[] args) {
)
例如:
示例Android代码:
public class Source1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.source1_layout);
Intent intent = getIntent();
int pickerValue = intent.getIntExtra("numEntered", 0);
}
程序(Test.java)中的示例Java代码:
public class Test {
public static void main(String[] args) {
System.out.println("Enter number: ");
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
...
}
}
如何将pickerValue
传递给Test
类的main方法(启动main方法的逻辑)?我想在main方法中使用num = pickerValue;
(替换Scanner
)。这是怎么做到的?
另外,我所拥有的打印语句System.out.println(...);
会直接转换为Android UI并在屏幕上打印,还是我必须修改它们?
答案 0 :(得分:1)
您应该尝试将UI与逻辑分开。根据实际收集输入的部分的输入,提取计算内容的部分。这样,逻辑方法(或类)可以与几种输入收集方法一起重用。
例如,Calculator类不应具有以下方法:
/**
* asks for two numbers A and B, reads them from the keyboard, and displays the result
* of A^B on the screen
*/
public void power() {...}
/**
* asks for a number A, reads it from the keyboard, and displays the square root
* of A on the screen
*/
public void squareRoot() {...}
相反,它应分为两类:
public class Calculator {
/**
* returns a^b
*/
public double power(double a, double b) {...}
/**
* returns the square root of a
*/
public double squareRoot(double a) {...}
}
public class ConsoleCalculator {
private Calculator calculator;
public ConsoleCalculator(Calculator calculator) {
this.calculator = calculator;
}
/**
* asks for two numbers A and B, reads them from the keyboard, uses
* the calculator to compute A^B, and displays the result on the screen
*/
public void power() {...}
/**
* asks for a number A, reads it from the keyboard, uses the calculator to
* compute the square root of A and displays the result on the screen
*/
public void squareRoot() {...}
}
这样,构建AndroidCalculator很容易,因为硬核数学逻辑封装在Calculator类中,而不关心输入来自何处。
答案 1 :(得分:1)
您必须重新编写Java逻辑才能被Android框架理解。根据应用程序的复杂程度,这可能也可能不容易。
例如,使用您发布的Test类
Sample Java Code from program:
public class Test {
public static void main(String[] args) {
System.out.println("Enter number: ");
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
...
}
}
这很容易成为
public class Source1 extends Activity {
TextView number;
EditText enterText;
String result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.source1_layout);
//inflate your components from XML
result = (TextView)findViewById(R.id.resultId);
enterText = (EditText)findViewById(R.id.enterTextId);
//Get the value from the user
//print it to the screen
String userWrites = enterText.getText().toString();
result.setText(userWrites);
}
你似乎走在了正确的轨道上。希望这有帮助