我使用以下代码生成自定义ListView。一切都运行正常,但是当用户点击列表视图时,我无法转到另一个类,因为Intents不能在非Activity类中使用。 有没有办法为下面的代码启动活动???
public class CustomAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
public CustomAdapter(MainActivityList mainActivity, String[] prgmNameList,
int[] prgmImages) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = mainActivity;
imageId = prgmImages;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv = (TextView) rowView.findViewById(R.id.textViewlist);
holder.img = (ImageView) rowView.findViewById(R.id.imageViewlist);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(position)
{
case 0:
{
//Intent is not working here
//Here i need some help
}
}
}
});
return rowView;
}
}
我被困在项目的这一部分,请帮助我..
答案 0 :(得分:12)
使用活动上下文
Intent intent = new Intent(context,AnotherActivity.class);
context.startActivity(intent);
答案 1 :(得分:1)
为了不过度使用Adapter
,我会使用registerForContextMenu(convertView)
为每个行注册一个上下文菜单。这样,您就必须在onCreateContextMenu()
之外实施onContextItemSelected()
和Adapter
,可能在填充Activity
的{{1}}内,并定义<{1}}里面的ListView
,它可以正常工作。
以下是一个例子:
startActivity()
答案 2 :(得分:1)
你也可以这样做..
public void onClick(View v){
Intent yourIntent = new Intent(context,AnotherActivity.class);
yourIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
v.getContext().startActivity(yourIntent);
}
答案 3 :(得分:1)
TextView mealName = (TextView) view.findViewById(R.id.mealNameDietTXT);
mealName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
SessionClass.subMealID=mealsArray.get(position).getMealComponentId();
Intent i = new Intent(dietRadioAdapter.this.context, dietDetails.class);
dietRadioAdapter.this.context.startActivity(i);
}
});
答案 4 :(得分:0)
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int pos, long arg3) {
Intent intent= new Intent(currentClass.this,secondActivity.class);
currentClass.this.startActivity(intent);
finish();
}
});