Implementing Code Behind Clickable TextViews
I just started working with clickable TextViews 开发者_如何学Goin Eclipse. The line in the code below:
t2.setOnClickListener(this); seems to be having a problem.
I have tried a variety of methods like setOnTouchListener etc. to handle the click events of a user clicking my TextViews but I am having trouble determining which method (if any) is appropriate behind clickable TextViews.
public class Soundboard extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.soundboard);
TextView t2 = (TextView) findViewById(R.id.textView5);
t2.setFocusable(true);
t2.setOnClickListener(this);
t2.setOnClickListener(new View.setOnClickListener() {
public void onClick(View view) {
mp.start();
}
});
}
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
TextView t2 = (TextView) findViewById(R.id.textView);
t2.setOnClickListener(new View.setOnClickListener() {
public void onClick(View view) {
mp.start();
}
});
OR
TextView t2 = (TextView) findViewById(R.id.textView);
t2.setOnClickListener(this);
@Override
public void onClick(View v) {
if(v == t2){
// logic
}
}
This is the right way of setting on click listeners.
In your code above, you are setting the onClickListener
twice, which is unnecessary. The second time you set it will override the first, and the result of the click should be the execution of mp.start();
Can you describe in more detail what your problem is? What is or isn't happening when you run your app?
精彩评论