从另一个班级获取列表(Android)
问题描述:
好吧,我已经在这里搜索并试图了解现有的问题,但有困难,所以我发布这个。 在我的应用程序卡中显示使用recyclerview。当用户单击任何项目时,其索引(int i)将传递给CardViewActivity,并显示与该值匹配的卡片。 我试图在列表中显示数据卡<>。如果我将它保存在同一个文件中,我没有任何问题。但是,我想将它保存在一个不同的通用文件中,并从其他类访问它。我目前的代码正在进入循环我猜,我不能看到它是什么。从另一个班级获取列表(Android)
请帮忙。
我Person.class是:
class Person {
String name;
String age;
int photoId;
List<Person> persons;
Person(String name, String age, int photoId) {
this.name = name;
this.age = age;
this.photoId = photoId;
}
protected void initializePerson(){
persons = new ArrayList<>();
persons.add(new Person("Emma Wilson", "23 years old", R.drawable.emma));
persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.lavery));
persons.add(new Person("Lillie Watts", "35 years old", R.drawable.lillie));
CardViewActivity cardViewActivity = new CardViewActivity(persons, this);
cardViewActivity.setDetails();
}
}
我试图从CardViewActivity访问:
public class CardViewActivity extends Activity {
TextView personName;
TextView personAge;
ImageView personPhoto;
List<Person> persons;
Person person;
int id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
id = intent.getIntExtra("position", 0);
Toast.makeText(this, "Message"+id, Toast.LENGTH_SHORT).show();
//Person person = new Person();
person.initializePerson();
setContentView(R.layout.cardview_activity);
personName = (TextView)findViewById(R.id.person_name);
personAge = (TextView)findViewById(R.id.person_age);
personPhoto = (ImageView)findViewById(R.id.person_photo);
//personName.setText(persons.get(0).name);
setDetails();
}
CardViewActivity(List<Person> persons, Person person){
this.persons = persons;
this.person = person;
}
public void setDetails(){
//this.persons = persons;
//Toast.makeText(this, "Inside setDetails() and id is "+i, Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Person name is "+persons.get(i).name, Toast.LENGTH_SHORT).show();
int i = id;
personName.setText(persons.get(i).name);
//personAge.setText(persons.get(i).age);
//personPhoto.setImageResource(persons.get(i).photoId);
}
private void initializeData(){
persons = new ArrayList<>();
persons.add(new Person("Emma Wilson", "23 years old", R.drawable.emma));
persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.lavery));
persons.add(new Person("Lillie Watts", "35 years old", R.drawable.lillie));
}
}
答
执行以下
public class SomeConstant {
public static List<String> someList = new ArrayList<String>();
static {
someList.add("John");
someList.add("adam");
}
}
//在这里你会调用你创建的列表 public class SomeClass {
public static void main(String[] args) {
System.out.println(SomeConstant.someList);
}
}
你可以让列表为静态吗? – clavio
请详细说明。 – swap
根据你要做什么,你可以使卡片列表是静态的。你可以把它放在一个单独的类,并从其他类像Class.cardList – clavio