如何以编程方式在Android中将视图添加到gridview? [英] How to add view to gridview programmatically, android?

查看:60
本文介绍了如何以编程方式在Android中将视图添加到gridview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了2个列的gridview。
我需要在运行时在每列中动态创建一个按钮和一个textview。
我无法编写其baseadapter类。
我应该如何在gridview中增加视图。

I have created a gridview of 2 coloumns. I need to have a button and a textview which are created dynamically at runtime in each column. I am unable write its baseadapter class. How should i inflate my view in the gridview.

这是我的适配器类

    public class Adapter extends BaseAdapter {
    Context con;
    Integer[] m;

    public Adapter(Context c) {
        con = c;
    }

    public Adapter(Integer[] x) {
        m = x;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return m.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return m[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Button btn = new Button(con);
        TextView textview =new TextView(con);


        return null;
    }

}


推荐答案

您可以执行以下操作:

public class Adapter extends BaseAdapter {
Context con;
Integer[] m;

public Adapter(Context c, Integer[] x) {
    con = c;
    m = x;
}



@Override
public int getCount() {
    // TODO Auto-generated method stub
    return m.length;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return m[position];
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
   LinearLayout layout = new LinearLayout(mContext);
    layout.setLayoutParams(new GridView.LayoutParams(
            android.view.ViewGroup.LayoutParams.FILL_PARENT,
            android.view.ViewGroup.LayoutParams.FILL_PARENT));
    layout.setOrientation(LinearLayout.HORIZONTAL);

    Button btn = new Button(mContext);
    btn.setLayoutParams(new LinearLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
    btn.setText("Btn " + position);

    TextView textview = new TextView(mContext);
    textview.setLayoutParams(new LinearLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
    textview.setText("TV " + position);
    textview.setTextColor(Color.RED);

    layout.addView(textview);
    layout.addView(btn);

    return layout;
}

}

它将起作用:)

这篇关于如何以编程方式在Android中将视图添加到gridview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆