有兩個文本框和一個數組,想要將數組索引號寫在文字框1,然後在點擊Calculate按鈕時,在文本框2中獲取數組值。
"MainActivity.java"代碼如下:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button B1 = (Button) findViewById(R.id.button1);
B1.setOnClickListener(new View.OnClickListener() {
final EditText ET2 = (EditText) findViewById(R.id.editText2);
public void onClick(View v) {
final int[] oil={20,30,40,50,60,70,80,90,100};
final String str = String.valueOf(R.id.editText1);
final int y = Integer.parseInt(str);
final int z = oil[y];
ET2.setText(z);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
"activity_main.xml"代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="67dp"
android:ems="10"
android:inputType="number" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Calculate" />
大概就是這樣,你寫的錯誤太多了
private Button b1;
private EditText e1,e2;
private final int[] oil={20,30,40,50,60,70,80,90,100};
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
e1 = (EditText) findViewById(R.id.editText1);
e2 = (EditText) findViewById(R.id.editText2);
b1 .setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String string = e1.getText().toString();
int index = Integer.valueOf(string);
int z = oil[index ];
e2.setText(z);//這裡不能直接這樣寫 會報錯 傳遞int值代表的是id
應該寫成e2.setText(""+z);或者e2.setText(String.valueOf(z));
}
});
}