I have created a For Loop which sets each ImageView an ID and a ClickListener. When the click is pressed, the OnClickListner either doesn't seem to be able to find the ID, or isn't called at all.
public int[] myResources = {R.id.bblock1, R.id.bblock2, R.id.bblock3, R.id.bblock4, R.id.bblock5, R.id.bblock6, R.id.bblock7, R.id.bblock8};
ImageView[] bblock = new ImageView[7];
for(int i = 0; i==myResources.length; i++) {
bblock[i]=(ImageView)layout.findViewById(myResources[i]);
bblock[i].setOnClickListener(ActivityCheck);
}
View.OnClickListener ActivityCheck = new View.OnClickListener(){
public void onClick (View v){
if( v.getId() == (R.id.bblock1)){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/#!/itz_jonno"));
startActivity(browserIntent);
}
^^ The OnClickListener is not able to to find the view.
Although, WITHOUT using the array and loop the code below does work:
ImageView bblock1=(ImageView)layout.findViewById(R.id.bblock1);
bbblock1.setOnClickListener(ActivityCheck);
Any ideas why the array wont work, but the standard code will?
Change i==myResources.length into i < myResources.length.
The current loop will exit immediately unless 0 == myResources.length.
(The whole event listener thing was a nice decoy though.)
Besides problem with a loop, your Listener will work only for R.id.block1 , it will egnore events for all other views. What exactly you are trying to achieve?
for(int i = 0; i==myResources.length; i++) {
bblock[i]=(ImageView)layout.findViewById(myResources[i]);
bblock[i].setOnClickListener(
new View.OnClickListener(){
public void onClick (View v){
if( write u r checking condition here ){
start u r suitable activity here.
}
);
}
Related
Whenever the user presses the button, the text of the TextView, as well as the background image of TextView, is changed. I have created an int[] array to store the id of drawable to use in TextView.setBackgroundResource(array[index]) . But on incrementing the index the background is not changed. I even tried hardcoded index for array[] but it still sets first element image.
//j and drawable array are global variable.
int j=1;
int[] drawablearray=new int[]{R.drawable.girl,R.drawable.beach,R.drawable.flower};
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(j<drawablearray.length-1){
j++;
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
}else{
j=0;
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
}
});
It seems everthing OK in your code.
Did you initialised nextButton properly?
Probably your click is not working.
UPDATE
I have updated your code:
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<drawablearray.length){
quoteTextView.setBackgroundResource(drawablearray[j]);
quoteTextView.getBackground().setAlpha(150);
j++;
}else{
quoteTextView.setBackgroundResource(R.drawable.girl);
quoteTextView.getBackground().setAlpha(150);
}
}
});
For the first 3 clicks it will show three different images then sets to default image
Your j variable must be 'global'. It means that it must a member of your Activity or Fragment but not a variable inside your method
Instead of the "if" condition I suggest you to use:
j = (j+1) % drawablearray.length;
Then the variable j must be a field of your java class (declare it outside every method)
hows it going? I'm creating a little training app for a project, its going fine except for a formatting problem im getting. So, ive a csv file with a name and age for a client. an array is created from this, then I've got a scroll View containing a grid layout and i create Image Buttons from the client array. that's all fine. ive got an add client button at the end of this, the button and its activity work fine, but when you come back to the main screen, the buttons are all screwed up (huge, misplaced etc). So i figured i would loop through and delete all the buttons and repopulate the main screen, except, since i programmatically created them, i cant figure out how to find them to delete them. i tried setting their id's to the index of the array, but then i get a null pointer error.
Function where the buttons are created:
public void fillActivity_main(){
if(listPopulated == false) { // check to see if its aready been created
populateClientList();//fill array with client objects
listPopulated = true;
}
//setup asset manager
AssetManager am = getApplicationContext().getAssets();
//Create the "GridLayout Image Board"
GridLayout buttonBoard = (GridLayout) findViewById(R.id.buttonboard);
int idealWidth = buttonBoard.getWidth(); //get width of the board
int idealHeight = buttonBoard.getHeight() / 2;//same
//create the Listeners, this is a place holder for now but will eventually use SetCurrentClient() (or maybe just switch to Start screen, with the current client?)
View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CLICK AT: " + v.getId());
Client temp = clientList[v.getId()];
Intent i = new Intent(getApplicationContext(), DisplayClient.class);
System.out.println(temp.getName());
i.putExtra("name", temp.getName());
System.out.println(i.getStringExtra("name"));
i.putExtra("age", Integer.toString(temp.getAge()));
startActivity(i);
}
};
int j = 0; //used the keep track of the id's we set for the buttons
for (int i = 0; i < clientList.length; i++) {
if (clientList[i] != null) {
//creation and ID setting
ImageButton imgbutton = (ImageButton) new ImageButton(this);
imgbutton.setId(i);
//Layout shit
imgbutton.setImageResource(R.mipmap.ic_launcher);
imgbutton.setMinimumWidth(idealWidth);
imgbutton.setMinimumHeight(idealHeight);
imgbutton.setOnClickListener(imageClickListener);
//check and set image
if(clientList[i].getClientImage().equals(" ")) {
try{
imgbutton.set(am.openFd(clientList[i].getClientImage()));}
catch(Exception ex){
ex.toString();
}
Log.d("ClientImageCheck", "No picture found for " + clientList[i].getName());
}
buttonBoard.addView(imgbutton);
j++;
}
}
//create the new Client Button at the end of all the rest.
Button newClientButton = (Button) new Button(this);
newClientButton.setText("+"); // obvious
newClientButton.setLayoutParams(new LinearLayout.LayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT));
newClientButton.setWidth(idealWidth);
newClientButton.setHeight(idealHeight);
View.OnClickListener newClientListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), CreateClientForm.class);
startActivityForResult(i, 199);
//System.out.println("Doing good so far, leaving the createclient form bnut still in main");
}
}; // create listener
newClientButton.setOnClickListener(newClientListener); // assign listener
buttonBoard.addView(newClientButton); //add the button the buttonBoard, after all the clients have been added
}
Function where i do the deleting:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check which request we're responding to
if (requestCode == 199) {
// Make sure request was successful
if (resultCode == RESULT_OK) {
// The user made a name and crap.
Bundle extras = data.getExtras();
String name = extras.getString("name");
int age = extras.getInt("age");
Client temp = new Client(name, age);
addClientToArray(temp);
System.out.println(name + "attempted add to array");
}
for(int i = 0; i<clientList.length; i++ ){
View v = findViewById(i);
((ViewManager) v.getParent()).removeView(v);
}
fillActivityMain();
}
if i've got the logic right, the 'i' in the loop should be the appropriate id. Granted, the teach has kind of thrown us in the deep end for this project, never taken mobile apps or anything, so all this code is the result of me googling issues as i run into them. I've read the basics for Views, intents, etc, but there must be something i'm missing.
I've tried making the gridLayout that the buttons sit on a class variable so i could call it buttonBoard.removeView(i) or something.
ive also tried `
for(int i = 0; i<clientList.length; i++ ){
ImageButton btn = (ImageButton) findViewByid(i);
((ViewManager) v.getParent()).removeView(btn);
}
Can you add the replacement images at the same time that you delete the existing images? If so, try this:
for(int i = 0; i < buttonBoard.getChildCount(); i++) {
ImageButton tempButton = (ImageButton) buttonBoard.getChildAt(i);
tempButton.setVisibility(View.INVISIBLE);
buttonBoard.addView(yourImageButtonHere, i); //adds a new ImageButton in the same cell you are removing the old button from
buttonBoard.removeView(tempButton);
}
This approach should also prevent the GridLayout from rearranging where the children are. I believe the default behavior if you delete a child view is that the GridLayout will re-order the children so there is not empty cell at the beginning of the grid. I hope that makes sense.
There is so much wrong with this approach.
Mainly you don't have to create the ImageButtons manually and add them to the GridLayout. That is what recycled views such as GridView or RecyclerView are for. In fact you should use those to avoid OutOfMemoryError from having too much images in your layout.
But also you cannot just call setId(i) in the for loop. Android holds many ids already assigned and you can never be sure whether the id is safe. (Unless you use View.generatViewId())
And since you only want to remove all views added to your GridLayout why don't you just call removeAllViews() on the buttonBoard?
I have a dynamic array of buttons and I would like to know how to handle the onclick on every button?
Thanks
I don't see a need to create a new OnClickListener for each button -- all the buttons could share a single listener.
private OnClickListener myListener = new OnClickListener() {
public void onClick(View v) {
Object tag = v.getTag();
// Do something depending on the value of the tag
}
};
...
for (int i=0; i < btns.length; ++i) {
btns[i].setOnClickListener(myListener);
btns[i].setTag(some_identifying_information);
}
Of course, you could create a unique OnClickListener for each button, and take advantage this way:
for (int i=0; i < btns.length; ++i) {
final Button btn = btns[i];
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do something depending on the value of btn, which you're allowed
// to reference here because it was declared final above.
}
});
}
The same way you would on a single button...
Set an on click listener, if you have an Array it would look something like this:
btns[0].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
btns[1].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
//etc.
If you want all of them to do the same thing you could use a for loop to loop over the array like this:
for(int i = 0; i< btns.length; i++){
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v){
//do something
}
});
}
I don't know exactly what you are doing but if you have an Array of Buttons it is likely that you should probably be using an Adapter with a ListView or something instead of how every you are doing it now.
Without seeing some code or more of an explanation, it's hard to really answer your question, but here are some tips:
Before we get to the listeners, we have to make sure that each of the dynamically created buttons knows how to respond to a click event. You can use the setTag method on a button to attach an arbitrary Object to it. This Object will represent how the Button acts when clicked. You can just use Integers as this Object (perhaps some constant values) or if each button needs some unique data, create a class that maintains both how the button needs to act when clicked AND the data you need (or at least a reference to it).
Then, you can initialize one single listener that handles all of your button clicks. In the onClick method of this listener place a conditional that branches to handle all of your click cases. Set this listener on all of your dynamic buttons as you create them. At the start of your onClick, get the Tag from the View parameter of the onClick method (this view will be the button that was clicked), and use that to decide which branch of the conditional to take.
Hope this helps. If you make your question more specific, we'll be able to offer some more detailed assistance.
I have programatically defined a set of imagebuttons in a for loop. For each button, I defined its setOnClickListener function which will put some data in the intent and then switch activity. However, it seems like no matter which button I clicked on, the extra data retrieved is set the the last value int he for loop. See code here:
public void onCreate(Bundle savedInstanceState) {
<...>
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlayout);
for (int i=1; i<=maxMapLoc; i++ ) {
mapLocation = i;
ImageButton btnMapLoc = new ImageButton(FirstActivity.this);
RelativeLayout.LayoutParams vp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnMapLoc.setLayoutParams(vp);
btnMapLoc.setBackgroundColor(Color.TRANSPARENT);
btnMapLoc.requestLayout();
String imgName = "map_loc_" + mapLocation;
int id = getResources().getIdentifier(imgName,"drawable",getPackageName());
btnMapLoc.setImageResource(id);
int imgMapLoc = 2000 + mapLocation;
btnMapLoc.setId(imgMapLoc);
rl.addView(btnMapLoc, vp);
btnMapLoc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("MapLocation", mapLocation);
startActivity(intent);
}
});
Any idea what I did wrong?
Thanks.
You could add a tag to your button with the current mapLocation value.
btnMapLoc.setTag(i);
...
// In onClick
intent.putExtra("MapLocation", v.getTag());
...
The reason why you only get the last value of mapLocation is that the code inside your onClick() is run when the user pushes a button. In other words your are querying mapLocation long after the loop built your buttons. You need to create a reference to the current mapLocation in each loop iteration, like with the tag feature.
I will try to explain my problem. The code below as you can see try to add some textviews and buttons as the array get from another class.
public class Breakfast extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
sv.addView(ll);
if (extras != null) {
String food[]=extras.getStringArray("food");
String foodCateg[]=extras.getStringArray("foodCateg");
int K=0;
for (int i = 0; i < food.length/3; i++) {
TextView foodDay = new TextView(this);
foodDay.setText("Day "+ (i+1));
ll.addView(foodDay);
for (int j=K;j<K+3;j++){
Button contfood= new Button(this);
contfood.setText(food[j]);
ll.addView(contfood);
}
K=K+3;
}
this.setContentView(sv);
}
}
My question is how can I know what of this buttons are clicked on the screen?? Because in the case of what one of them are clicked (getting the text that have write before), I will do something or other thing.
ahhhhhhhhhhhhhhhhh yes I know how to do a ListActivity. But first I think in doing by hand because I don´t think how to symplify this...
Thank you for the answers of trying to build with everything a listview and then the method OnListItemClick, but I think that isn´t the solution.
I said that because when I insert the day for example (I Don´t put hear all the code...) but I do .setgravity .setSize .setbackgroundResource etc. And with the food for that day I use a diferent .setgravity and more parameters. So I think that with listview everything would have the same specifications... and that´s what I don´t like.
so... to know what button is pressed on the screen?
You could use contfood.setId(i) and work your way from there.
But what you are doing looks like you really want to create a ListActivity and use it's OnItemClickListener.
What you should do is put an id to each button "contfood". And then when you click on a button retrieve the id back to do the action you want.
Another way is to create the button and attach the method public void onClick(View view):
for (int j=K;j<K+3;j++){
Button contfood= new Button(this);
contfood.setText(food[j]);
ll.addView(contfood);
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), xxx.class);
startActivityForResult(myIntent, 0);
}
}
and add the parameters within the method.