我试图显示基于RadioButtons
的数组的内容。我使用两组按钮。按钮应该指向我数组中的[x, y]
。需要显示阵列的String
值(使用Toast
)
是的,我是新手,但我试着找出几个类似的例子,但运气不好。
public class MainActivity extends Activity {
String[][] tipSize = {
{"N/A","N/A","Pink","Lt Blue","Purple","Yellow","Brown","Orange","Tan","Blue","White","Beige"},
{"N/A","Pink","Lt Blue","Purple","Yellow","Brown","Orange","Green","Tan","Blue","White","Beige"},
{"N/A","N/A","Pink","Purple","Turquoise","Yellow","Green","Tan","Blue","White","Red","No Tip"},
{"Pink","Lt Blue","Purple","Yellow","Orange","Green","Tan","Blue","Red","Beige","Gray","N/A"},
{"Pink","Lt Plue","Purple","Orange","Green","Tan","Blue","White","Beige","Black","Gray","N/A"},
{"Pink","Lt Blue","Yellow","Brown","Orange","Green","Tan","Blue","White","Beige","Black","N/A"},
{"Pink","Lt Blue","Yellow","Brown","Tan","Blue","White","Red","Beige","Black","No Tip","N/A"},
{"Pink","Lt Blue","Purple","Yellow","Orange","Green","Tan","Blue","Red","Beige","Gray","N/A"},
};
private RadioGroup dispenser,ounce_pg;
private RadioButton disp,o_pg;
String tip = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button finishBtn = (Button) findViewById(R.id.button1);
finishBtn.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.this.showit();
}
});
}
protected void showit() {
// TODO Auto-generated method stub
disp = (RadioButton) findViewById(R.id.dispenser);
o_pg = (RadioButton) findViewById(R.id.ounce_pg);
tip = String tipSize [disp,o_pg];
// tip is the displayed answer (Color of tip), tipSize[][] is the Array, disp is RadioButton 1 - o_pg is Radio Button 2 values.
Toast.makeText(MainActivity(),tip,Toast.LENGTH_LONG).show();
}
}
一种快速而肮脏的方法是创建一个简单的字符串数组,其中包含一个分隔的字符串,将第二个值分组在一起,然后使用split函数,该函数本身返回一个字符串数组来获取单个值。
String [] allTips = {"a;b;c", "d;e;f"};
String [] sometips = alltips[1].split(";")
String tip = sometips[2];
会产生字母f
这一行有很多问题:
tip = String tipSize [disp,o_pg];
[disp,o_pg]
应该是[disp][o_pg]
,因为访问2D数组是通过array [x][y]
完成的String tipSize
没有意义,你不能在这里声明类型。如果你做了(String)
,它将是一个强制转换,这将是好的(但这将是多余的,因为你有一个String
数组-从String
转换成String
不做任何事情)。disp
和o_pg
应为int
。
这是因为当访问索引时,你不能将Object传递给数组,数组不会为你"搜索"。这意味着你需要弄清楚你想要进入哪些职位,并把它们传递出去。还要记住索引从0
开始,而不是从1
开始。
tip = tipSize [0][0]; //first element of the first array ("N/A")