从适配器启动Intent

时间:2016-12-01 23:06:51

标签: android android-intent gridview

我按照本教程android-material-design-gridview

我想从这个基本适配器开始意图;

public class CustomAndroidGridViewAdapter extends BaseAdapter {

private Context mContext;
private final String[] string;
private final int[] Imageid;

public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
    mContext = c;
    this.Imageid = Imageid;
    this.string = string;
}



@Override
public int getCount() {
    return string.length;
}

@Override
public Object getItem(int p) {
    return null;
}

@Override
public long getItemId(int p) {
    return 0;
}

@Override
public View getView(int p, View convertView, ViewGroup parent) {
    View grid;
    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


    if (convertView == null) {

        grid = new View(mContext);
        grid = inflater.inflate(R.layout.gridview_custom_layout, null);
        TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
        ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
        textView.setText(string[p]);
        imageView.setImageResource(Imageid[p]);
    } else {
        grid = (View) convertView;
    }

    return grid;
}}

这是MainActivity

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;

public static String[] gridViewStrings = {
        "Helper InSiti",
        "Parkir InSiti",


};
public static int[] gridViewImages = {
        R.drawable.icon_helper_insiti,
        R.drawable.icon_parkir_insiti,

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    gridView = (GridView) findViewById(R.id.grid);
    gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));

    initInstances();
}

private void initInstances() {
    rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
    collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
    collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}}

它包含2个ImageView图标,用于按钮onClick到另一个活动 我尝试了很多方法来启动从MainActivity到另一个活动的意图,但是失败了...... 请帮忙......

1 个答案:

答案 0 :(得分:0)

由于您正在接收适配器的构造函数中接收上下文:

public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
    mContext = c;
    this.Imageid = Imageid;
    this.string = string;
}

使用此上下文启动Intent,例如:

 Intent intent = new Intent(mContext, OtherActivity.class);
 mContext.startActivity(intent);