如何以编程方式在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;
}
}
它将起作用:)