【发布时间】:2019-03-24 06:34:12
【问题描述】:
我是 Android 新手。
我在我正在学习的书中找到了这段代码。它没有正确解释
我创建了一个 Drink java 类
然后我在我的活动中使用了drinks[]。单击时,它使用意图将单击数组的 ID 传递给另一个活动。
现在在其他活动中,我想显示饮料的名称图像和我们存储在数组中的描述
我了解到我们已经将数组 ID 存储在 Drinks 类对象中
但是为什么我们使用getter方法来获取名称和描述以及图像。
它们是不是与数组相连?
他们里面没有代码?
那么实际发生了什么
谁能解释一下?
Drinks.java类代码
Class Drinks
{
private String name ;
private String description ;
private int rid ;
public static final Drinks[] drinks = {
new Drinks("Latte", "A couple of espresso shots with steamed milk",
R.drawable.latte),
new Drinks("Cappuccino", "Espresso, hot milk, and a steamed milk foam",
R.drawable.cappuccino),
new Drinks("Filter", "Highest quality beans roasted and brewed fresh",
R.drawable.filter)
};
public Drinks(String name, String description, int rid) {
this.name = name;
this.description = description;
this.rid = rid;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public int getRid() {
return rid;
}
}
-----------------------------------------
我正在使用饮料 [] 并传递其 ID 的活动代码
listDrinks = findViewById(R.id.listDrinks);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1 ,Drinks.drinks);
listDrinks.setAdapter(adapter);
listDrinks.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Main2Activity.this , Main3Activity.class);
intent.putExtra("id",id);
startActivity(intent);
}
});
我传递数组 id 并使用 getter 方法设置名称描述和要显示的图像的其他活动
textView = findViewById(R.id.textname);
text_description = findViewById(R.id.text_description);
imageView = findViewById(R.id.photo);
Intent intent= getIntent();
int drinkId = Integer.parseInt(intent.getStringExtra("id"));
Drinks d = Drinks.drinks[drinkId];
textView.setText(d.getName());
text_description.setText(d.getDescription());
imageView.setImageResource(d.getRid())
;
【问题讨论】:
标签: android listview android-activity