Android 如何使用自定义ListView适配器切换活动?
我正在尝试使用自定义ListView适配器切换到不同的活动,但在这样做时遇到了问题,因为有一个我似乎无法摆脱的错误 相关代码 类别表:Android 如何使用自定义ListView适配器切换活动?,android,listview,custom-adapter,Android,Listview,Custom Adapter,我正在尝试使用自定义ListView适配器切换到不同的活动,但在这样做时遇到了问题,因为有一个我似乎无法摆脱的错误 相关代码 类别表: public class CategoryTable extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.la
public class CategoryTable extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_table);
populateTable();
goToPreviousActivity();
}
private void populateTable() {
final ListView mListView = findViewById(R.id.listView);
Category 1 = new Category(" One");
Category 2 = new Category(" Two");
Category 3 = new Category(" Three");
Category 4 = new Category(" Four");
final ArrayList<Category> categoryList = new ArrayList<>();
categoryList.add(1);
categoryList.add(2);
categoryList.add(3);
categoryList.add(4);
CategoryListAdapter adapter = new CategoryListAdapter(this, R.layout.adapter_view_layout, categoryList);
mListView.setAdapter(adapter);
}
private void goToPreviousActivity() {
ImageButton btn = findViewById(R.id.backButton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
public static Intent makeIntent(Context context) {
return new Intent(context, CategoryTable.class);
}
}
如果需要,我将提供任何其他相关代码/详细信息
任何帮助都将不胜感激
您的AllToolsTable.makeIntent()
方法需要一个Context
参数。通常,您可以使用类似于AllToolsTable.makeIntent(MainActivity.this)
的东西,因为Activity
是Context
的子类。但是,CategoryListAdapter
不是
因此,您需要以某种方式获得上下文
对象
幸运的是,getView()
方法传递给您一个非空的ViewGroup父对象,并且所有视图都有一个上下文。因此,您可以使用以下代码替换意图创建:
Context context = parent.getContext();
Intent intent = AllToolsTable.makeIntent(context);
Intent-Intent=AllToolsTable.makeIntent(CategoryListAdapter.this);可能是这句话听起来有错误。因为你需要传递活动上下文。啊,是的,这很有效!一个简单的修复,谢谢。我以后会记住的。
public class AllToolsTable extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_tools_table);
}
public static Intent makeIntent(Context context) {
return new Intent(context, AllToolsTable.class);
}
}
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
Context context = parent.getContext();
Intent intent = AllToolsTable.makeIntent(context);