listview中textview响应部分文本点击事件
</pre> 要在listview的item上实现控件的点击事件,需要专门去写一个adapter类去继承onClickListener,再在主类里去具体的写onClick方法里的内容。<p></p><p> textView的部分文本点击事件需要对使用这个类SpannableString,其中setSpan方法可以对textView中的部分文本进行处理,包括点击事件,颜色样式等。</p><p> 在开始的时候我认为这两个点击事件会冲突,但最后证明是不影响的。</p><p><pre name="code" class="java">public class ContentAdapter extends BaseAdapter implements OnClickListener{
private List<String> mContentList;
private LayoutInflater mInflater;
private Callback mcallback;
public interface Callback //这个接口必须写,主类必须实现这个
{
public void click(View v);
}
public ContentAdapter(Context context, List<String> contentList,
Callback callback) {
mContentList = contentList;
mInflater = LayoutInflater.from(context);
mcallback = callback;
}
public int getCount() {
return mContentList.size();
}
@Override
public String getItem(int position) {
return mContentList.get(position);
}
@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
ViewHolder holder=null;
if(convertView == null)
{
convertView =mInflater.inflate(R.layout.list_anouncement, null);
holder = new ViewHolder();
holder.name=(TextView) convertView.findViewById(R.id.textView1);
holder.time=(TextView) convertView.findViewById(R.id.time);
final SpannableString aname = new SpannableString(holder.name.getText());
aname.setSpan(new ClickableSpan() {
@Override
public void onClick(View v) {
mcallback.click(v);
}
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.RED); //当这段文本既要颜色又要格式又要点击时就用这种方法解决
}
},aname.length()-6,aname.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.name.setText(aname);
holder.time.setText(getItem(position));
holder.name.setMovementMethod(LinkMovementClickMethod.getInstance());
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setTag(position);
return convertView;
}
public class ViewHolder
{
public TextView name;
public TextView time;
}
@Override
public void onClick(View v)
{
// mcallback.click(v); //一定不能写
}
}
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/9373790.html