gpt4 book ai didi

android - 如何以编程方式将 View 添加到 gridview,android?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:04:40 25 4
gpt4 key购买 nike

我创建了一个 2 列的 GridView 。我需要有一个按钮和一个 TextView ,它们是在运行时在每一列中动态创建的。我无法编写它的 baseadapter 类。我应该如何在 gridview 中扩展我的 View 。

这是我的适配器类

    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 - 如何以编程方式将 View 添加到 gridview,android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21107064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com