我是android开发的新手。我有10个不同的按钮,我想为每个按钮显示一个祝酒词。该消息类似于:
“这是按钮:” + numButton
其中numButton是传递给函数的道具。这是功能代码:
public void displayMensaje(View v) {
Toast.makeText(ActividadUno.this, "Test", Toast.LENGTH_SHORT).show();
}
这是xml:
<Button
android:id="@+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:layout_marginTop="400dp"
android:text="churro"
android:onClick="displayMensaje"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
答案 0 :(得分:2)
您可以将View
中的Button
强制转换为按钮文本。
类似的东西:
public void displayMensaje(View v) {
Button button = (Button) v;
String title = button.getText();
String message = "Test " + title;
Toast.makeText(ActividadUno.this, message, Toast.LENGTH_SHORT).show();
}
修改:
根据我对以下评论的理解,您的活动中有多个按钮,并且您希望在单击不同按钮时显示不同的值。
您可以拥有一个Map
,其中按键作为按钮标题,值作为营养值。
以下是如何实现此目标的一般示例:
public class MyActivity extends Activity {
// Your Message Format
private static final String MSG_FORMAT = "Item Name: %s\n"
+ "Fat: %s\n"
+ "Protein: %s\n"
+ "Calories: %s";
// A Map to hold info of all items
// Key = button title
// Value = Array containing item info
private Map<String, String[]> info = new HashMap();
// Assuming you have 3 buttons in your activity
private Button btnMilk;
private Button btnEggs;
private Button btnChicken;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
btnMilk = (Button) findViewById(R.id.btn_milk);
btnEggs = (Button) findViewById(R.id.btn_eggs);
btnChicken = (Button) findViewById(R.id.btn_chicken);
// 0 = Fat, 1 = Protein, 2 = Calories
String[] milkInfo = new String[]{"12", "20", "125"};
String[] eggsInfo = new String[]{"10", "50", "205"};
String[] chickenInfo = new String[]{"50", "5", "500"};
// load your Map with the data
info.put(btnMilk.getText(), milkInfo);
info.put(btnEggs.getText(), eggsInfo);
info.put(btnChicken.getText(), chickenInfo);
}
public void displayMessage(View v) {
Button button = (Button) v;
String title = button.getText();
// Get item info from your Map
String[] itemInfo = info.get(title);
// Create message using the format and values from the array
String message = String.format(MSG_FORMAT, title, itemInfo[0], itemInfo[1], itemInfo[2]);
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
希望这会有所帮助