在eoe.android论坛浏览时 发现很多人对这个问题有困惑 所以今天说一下
[代码 步骤]
1. 你要放入GricView 的布局比较复杂 包括一个image & text 且二者以线性排列
* 定义图片和文字的数组 供后续使用
int count = 5;
int[] image = {
R.drawable.beijing_001_big,R.drawable.beijing_002_big,R.drawable.beijing_003_big,R.drawable.beijing_004_big,R.drawable.beijing_005_big
};
String[] name = {
"贝贝","晶晶","欢欢","盈盈","妮妮"
};
* 定义包含二者的View
public View composeLayout(int i){
LinearLayout layout = new LinearLayout(activity);
layout.setOrientation(LinearLayout.VERTICAL);
ImageView iv = new ImageView(activity);
iv.setImageResource(image[i]);
layout.addView(iv,
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(activity);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setTextColor(Color.BLACK);
tv.setText(name[i]);
layout.addView(tv,
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
return layout;
}
2. 因为View 不是TextView 所有只能自己扩展BaseAdapter
public class ComplexLayoutAdapter extends BaseAdapter {
Activity activity;
public ComplexLayoutAdapter(Activity a){
activity = a;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return composeLayout(position);
}
}
3. 使用问题 因为不是今天的重点 就此略过 现在说下 更改 TextView 使之为红色的问题 当其被点击时
grid.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
//重置上次颜色为Color.BLACK
setLastColorBlack();
LinearLayout lLayout = (LinearLayout)arg1;
//ImageView lImage = (ImageView)lLayout.getChildAt(0);
TextView lText = (TextView)lLayout.getChildAt(1);
//lImage.setBackgroundResource(R.drawable.dot);
lText.setTextColor(Color.RED);
}
});
4. 当然 我们还需要把上次点击目标的字体颜色重置
* 定义变量 last 用于标记上次点击的ID
int last = 0;
* 修改 setOnItemClickListener() 如下:
grid.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
//重置上次颜色为Color.BLACK
setLastColorBlack();
LinearLayout lLayout = (LinearLayout)arg1;
//ImageView lImage = (ImageView)lLayout.getChildAt(0);
TextView lText = (TextView)lLayout.getChildAt(1);
//lImage.setBackgroundResource(R.drawable.dot);
lText.setTextColor(Color.RED);
//保存最新的上次ID
last = arg2;
}
});
public void setLastColorBlack(){
LinearLayout lastLayout = (LinearLayout)grid.getChildAt(last);
TextView lastText = (TextView)lastLayout.getChildAt(1);
lastText.setTextColor(Color.BLACK);
}
that's all!
6. emulator 运行截图:
现上传代码 供有需要的人!