我是 Android 开发的新手。我有 10 个不同的按钮,我想为每个按钮显示 toast 。消息是这样的:
"This is the button: " + numButton
其中 numButton 是传递给函数的 Prop 。这是函数代码:
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" />
最佳答案
您可以在 Button
中转换 View
并获取按钮的文本。
是这样的:
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();
}
编辑:
根据我从您下面的评论中了解到,您的 Activity 中有多个按钮,并且您希望在单击不同的按钮时显示不同的值。
您可以制作一个 map
,其中键作为按钮标题,值作为营养值(value)。
以下是如何实现此目的的一般示例:
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();
}
}
希望对你有帮助
关于java - 根据参数显示不同的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53034306/