How to make a recursive onClickListener for expanding and collapsing?
In plain english, I have a textview, and when I click on it I wan开发者_如何学JAVAt it to expand, and when I click on it again, I want it to compress. How can I do this? I've tried the below, but it warns on the final line about expander might not be initialized on holderFinal.text.setOnClickListener(expander);
So now the code:
final View.OnClickListener expander = new View.OnClickListener() {
@Override
public void onClick(View v) {
holderFinal.text.setText(textData);
holderFinal.text.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
holderFinal.text.setText(shortText);
holderFinal.text.setOnClickListener(expander);
}
});
}
};
No need to use nested overrides if you can use the tag property:
const int COLLAPSED = 0;
const int EXPANDED = 1;
// set initial value(s) somewhere
holderFinal.setTag(COLLAPSED);
holderFinal.text.setText(shortText);
holderFinal.text.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
int i = (int)holderFinal.getTag();
if (i == EXPANDED)
{
holderFinal.setTag(COLLAPSED);
holderFinal.text.setText(shortText);
}
else
{
holderFinal.setTag(EXPANDED);
holderFinal.text.setText(textData);
}
}
});
Coulnd't you just find out if you're in a compressed or expanded state? If so, just go with
final View.OnClickListener expander = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(inCompressedState(v){
holderFinal.text.setText(textData);
}else{
holderFinal.text.setText(shortText);
}
}
};
or something like that :)
Here is the solution:
holder.text.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
final View.OnClickListener ref = this;
holderFinal.text.setText(textData);
holderFinal.text.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
holderFinal.text.setText(shortText);
holderFinal.text.setOnClickListener(ref);
}
});
}
});
精彩评论