如何在ArrayAdapter中传递任何类名

时间:2019-06-23 20:30:08

标签: java

我在此类中有一个Food类,我有许多具有类名称的数组,并且我正在尝试将此类名称传递给ArrayAdapter

package foodapp.example.com.foodapp;

public class FoodCategories extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListView listfoods = getListView();
        ArrayAdapter<Food> listadapter = new ArrayAdapter<Food>(FoodCategories.this,android.R.layout.simple_list_item_1,Food.Foods);
        listfoods.setAdapter(listadapter);
    }
}

1 个答案:

答案 0 :(得分:0)

如果您确实需要将类名作为字符串传递,则需要单行代码,例如FoodCategories.class.getName()

您的代码:

public class FoodCategories extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ListView listfoods = getListView();
    ArrayAdapter<Food> listadapter = new ArrayAdapter<>(FoodCategories.class.getName(),android.R.layout.simple_list_item_1,);
    listfoods.setAdapter(listadapter);
  }
}