我是Android开发的新手,并且在改变活动时遇到了一些问题。我正在尝试从方法中更改活动,但我收到错误cannot resolve method startActivity
,并在参数结束时收到错误Cannot resolve constructor 'Intent (...)'
。我发现a question here有同样的问题,并试图将他们的回复实施到我的程序中,但没有快乐。
以下是代码:
public void open301(View view) {
startActivity(new Intent(CustomAdapter.this, ThreeZeroOne.class));
}
在查看上面链接的问题的回复之前,代码看起来像这样,但错误相同:
public void open301(View view) {
Intent openThree = new Intent(this,ThreeZeroOne.class);
startActivity(openThree);
}
完整代码:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
public class CustomAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
public CustomAdapter(selectGame SelectGame, String[] prgmNameList, int[] prgmImages) {
result = prgmNameList;
context = SelectGame;
this.imageId = prgmImages;
inflater = (LayoutInflater) context.getSystemService(Context.
LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return result.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tv;
ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.game_selection, null);
holder.tv = (TextView) rowView.findViewById(R.id.txt);
holder.img = (ImageView) rowView.findViewById(R.id.img);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "Beginning game " + result[position], Toast.LENGTH_SHORT).show();
}
});
return rowView;
}
public void open301(View view) {
Intent openThree = new Intent(this,ThreeZeroOne.class);
startActivity(openThree);
}
}
答案 0 :(得分:42)
您应该使用适配器的上下文:
public void open301(View view) {
Intent openThree = new Intent(context,ThreeZeroOne.class);
context.startActivity(openThree);
}
答案 1 :(得分:6)
要开始一个新活动,你需要一个上下文来开始,你当前的活动“BaseAdapter”不是一个Context,幸运的是每个视图都有一个Context,所以你可以这样做:
public void open301(View view) {
Intent openThree = new Intent(view.getContext(), ThreeZeroOne.class);
view.getContext().startActivity(openThree);
}
答案 2 :(得分:3)
首先,您应该获得Context
:
private Context context;
public CustomAdapter(Context context) {
this.context = context;
}
然后:
context.startActivity(openThree);
答案 3 :(得分:0)
您还可以传递消息
list = ['img3.png','img1.png','img2.png']