Reputation: 473
I have a table of 16 (4x4) TextViews
. If one of them is clicked, I want to change its color and mark or unmark it from a boolean array.
In my .xml, the TextViews
look like this:
<TextView
android:id="@+id/bonus0"
android:layout_width="0dip"
android:layout_height="50dip"
android:layout_weight="0.25"
android:layout_margin="1dip"
android:background="#FFFFFF"
android:textIsSelectable="false"
android:onClick="ClickTurnColor"
android:clickable="true"
android:textSize="25sp"
/>
So a click on the TextView
should start the ClickTurnColor()
function.
In this function, I need some variables from the onCreate()
function.
When I try to pass them as parameters of the ClickTurnColor()
function, I get errors.
Can anybody help me? Thanks!
Upvotes: 3
Views: 7263
Reputation: 36449
Declare the variables you need outside onCreate()
, initialize them in onCreate()
, then use them in the ClickTurnColor
method. You will have to revert its method definition so it only accepts in one parameter (the View):
public void ClickTurnColor (View v)
{
//implementation
}
Also, keep in mind, Java naming conventions dictate that methods should start with a lowercase letter.
Or take the non-xml approach and make the listener inside onCreate()
if you really must keep those variables local:
button.setOnClickListener (new OnClickListener () {
@Override
public void onClick (View v)
{
//use your variables here
}
});
However, now you will have to make those variables final
if they are not instance variables and you are keeping them local to onCreate()
.
Also, since you do mention that you have a grid, you coul try using a GridView
and use an OnItemClickListener
. It still comes with the caveats that I mentioned before (either make the local variables non-local or declare them as final
), but it depending on your needs, it may be cleaner.
Upvotes: 1