Way of setting of onClickListener() - java

I created a ImageView object(img) and pass some resources through the same object(img) to a Linear Layout with a for-loop. On each Iteration of the loop I invoke a setOnClickListener() on img(img.setOnClickListener()) to show a Toast that reflects the value of the loop controller variable (i). The code segment i tried is below:
for (i = 1; i <= 6; i++)
{
img = new ImageView(this);
img.setImageResource(R.drawable.thambu);
body.addView(img);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Details.this, Integer.toString(i) , Toast.LENGTH_LONG).show();
}
});
}
The thing is whenever i click on the Images that is generated, i have a Toast displaying 7.
I know why its displaying 7. but i want to display the index of the image that is being clicked.
(body is the id of a linear layout on which i pass an ImageView)
How can i do that on android. Thanks in advance.

for (i = 1; i <= 6; i++)
{
img = new ImageView(this);
img.setImageResource(R.drawable.thambu);
body.addView(img);
img.setTag(i);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int tagInt = (int) v.getTag();
Toast.makeText(Details.this, Integer.toString(tagInt) , Toast.LENGTH_LONG).show();
}
});
}
try this, i have used tags..

Actually, it's rather a general Java question.
You should do something like the following:
for (int i = 1; i <= 6; i++) {
img = new ImageView(this);
img.setImageResource(R.drawable.thambu);
body.addView(img);
final int j = i;
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Details.this, Integer.toString(j) , Toast.LENGTH_LONG).show();
}
});
}

Related

background color and font Family in editext should change when buttons are been clicked

I am trying to create an activity which contain an edittext, of which background color and fonts should be changed whenever the button is been clicked.
To perform these actions on the edittext, I have created two ArrayList of int value and saved all the color's id and the font's id in this ArrayList. whenever the button is clicked the background color didn't change but the color's Hexa code print in the edittext and these color codes comes with extra ff values in front of every color's code like #ff1EFA9D and in the font method I am getting an error that says:-
Unable to start activity ComponentInfo{com.nanb.alpha/com.nanb.alpha.postcreater}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=-1
I have tried to find the solution over the internet but didn't get any solution that satisfies the error.
code For changing the background color and font of the edittext is given below
private EditText editText;
private ImageButton color,font;
ArrayList<Integer> bgcolorlist = new ArrayList<Integer>(10);
ArrayList<Integer> fontstyle = new ArrayList<Integer>(6);
int fontstylename=R.font.abril_fatface,bgcolor=R.color.white,fontpostion = fontstyle.indexOf(fontstylename);
int postion = bgcolorlist.indexOf(bgcolor);
private void Initialization() {
cancel = view.findViewById(R.id.backbutton);
createnextbutton = view.findViewById(R.id.nextbutton);
editText = view.findViewById(R.id.textpost);
color = view.findViewById(R.id.bgcolorbutton);
font = view.findViewById(R.id.fontstyle);
}
//codes are for the background color changing
private void backgroundcolormethod() {
bgcolorlist.add(R.color.white);
bgcolorlist.add(R.color.darkGreen);
bgcolorlist.add(R.color.colorPrimaryDark);
bgcolorlist.add(R.color.colorAccent);
bgcolorlist.add(R.color.colorPrimary);
bgcolorlist.add(R.color.orange);
bgcolorlist.add(R.color.edittextbg5);
bgcolorlist.add(R.color.edittextbg4);
bgcolorlist.add(R.color.edittextbg3);
bgcolorlist.add(R.color.edittextbg2);
bgcolorlist.add(R.color.edittextbg1);
editText.setBackgroundColor(bgcolor);
color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(postion == 10){
//Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(bgcolorlist.get(postion));
postion = 0;
}else{
int newpostion = postion + 1;
editText.setText(bgcolorlist.get(newpostion));
postion = newpostion;
}
}
});
}
//codes for changing the fonts
private void fontstylemethod() {
fontstyle.add(R.font.abril_fatface);
fontstyle.add(R.font.cedarville_cursive);
fontstyle.add(R.font.alfa_slab_one);
fontstyle.add(R.font.annie_use_your_telescope);
fontstyle.add(R.font.aclonica);
fontstyle.add(R.font.aguafina_script);
fontstyle.add(R.font.arizonia);
editText.setTypeface(Typeface.defaultFromStyle(fontpostion));
font.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fontpostion == 6){
Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(fontstyle.get(postion));
fontpostion= 0;
}else{
int newpostion = fontpostion + 1;
editText.setText(fontstyle.get(newpostion));
fontpostion = newpostion;
}
}
});
}
Help me to solve these errors.
Try changing your codes to this:
ArrayList<Integer> bgcolorlist = new ArrayList<Integer>(11);
ArrayList<Integer> fontstyle = new ArrayList<Integer>(7);
int fontpostion = 0;
int postion = 0;
private void Initialization() {
cancel = view.findViewById(R.id.backbutton);
createnextbutton = view.findViewById(R.id.nextbutton);
editText = view.findViewById(R.id.textpost);
color = view.findViewById(R.id.bgcolorbutton);
font = view.findViewById(R.id.fontstyle);
}
//codes are for the background color changing
private void backgroundcolormethod() {
bgcolorlist.add(R.color.white);
bgcolorlist.add(R.color.darkGreen);
bgcolorlist.add(R.color.colorPrimaryDark);
bgcolorlist.add(R.color.colorAccent);
bgcolorlist.add(R.color.colorPrimary);
bgcolorlist.add(R.color.orange);
bgcolorlist.add(R.color.edittextbg5);
bgcolorlist.add(R.color.edittextbg4);
bgcolorlist.add(R.color.edittextbg3);
bgcolorlist.add(R.color.edittextbg2);
bgcolorlist.add(R.color.edittextbg1);
editText.setBackgroundColor(bgcolorlist.get(0));
color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(postion == 10){
//Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(bgcolorlist.get(postion));
postion = 0;
}else{
postion++;
editText.setText(bgcolorlist.get(postion));
}
}
});
}
//codes for changing the fonts
private void fontstylemethod() {
fontstyle.add(R.font.abril_fatface);
fontstyle.add(R.font.cedarville_cursive);
fontstyle.add(R.font.alfa_slab_one);
fontstyle.add(R.font.annie_use_your_telescope);
fontstyle.add(R.font.aclonica);
fontstyle.add(R.font.aguafina_script);
fontstyle.add(R.font.arizonia);
editText.setTypeface(Typeface.defaultFromStyle(fontstyle.get(0)));
font.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fontpostion == 6){
Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(fontstyle.get(postion));
fontpostion= 0;
}else{
fontpostion++;
editText.setText(fontstyle.get(fontpostion));
}
}
});
}

Android Pass value to another activity

I have a MainActivity with 30 buttons (Ids: imageButton1,imageButton2...). On the click event, I'm starting a new activity called KlikNaDugme:
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
buttons = new ImageButton[30];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
}
I'm trying to pass vr to the KlikNaDugme activity, which is declared as a public int.
KlikNaDugme Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_klik_na_dugme);
int x = getIntent().getExtras().getInt("vrijednost");
System.out.println(x);
}
The problem is that it always gets a value of 29. How can I pass the id correctly?
Store the value of i in the button's tag:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(getResources().getIdentifier("imageButton" + (i + 1), "id", this.getPackageName()));
buttons[i].setTag(i);
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(HomeActivity.this, KlikNaDugme.class)
myIntent.putExtra("vrijednost", Integer.parseInt(view.getTag().toString()));
startActivity(myIntent);
}
});
}
}
The problem lies here:
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
What you are doing is that you're creating an invalid resource reference and then finding your view upon that reference, which is obviously wrong. Remember findViewById() needs a resource id which is generated by Android Studio itself.
The solution is to save all of your 20-30 views references in an array and then use a loop to set click listeners on them
Add the vr value as tag to button and then use getTag() method to get the vr value inside onclicklistener
for(int i=0; i<buttons.length; i++) {
{
buttons[i] = (ImageButton) findViewById(R.id.imageButton + i);
vr = i;
buttons[i].setTag(vr); // This will se the vr value as tag
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int vr = (int)view.getTag() // this will get the vr value from view
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", vr);
startActivity(myIntent);
}
});
}
R.id.what_ever will give you an integer value that generated by android studio in R class not the what_ever string. You should use getResources().getIdentifier() to get correct id of resource and pass it to findViewById().
Please try this code. It will get you the correct id of ImageButtons:
buttons = new ImageButton[30];
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "imageButton" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = (ImageButton) findViewById(resID);
buttons[i].setTag(i);
//vr = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View args0) {
Intent myIntent = new Intent(HomeActivity.this,
KlikNaDugme.class).putExtra("vrijednost", (int)args0.getTag());
startActivity(myIntent);
}
});
}
Enjoy it.

How to get the id of a radio button in Java?

I've created pragmatically 5 radio groups with 4 radio buttons each. How can i get the Id of the radio buttons? Very important, i dont't want to use setOnCheckedChangeListener. Here is my code.
radioGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
radioGroup[i] = new RadioGroup(this);
radioGroup[i].setId(i);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answer[j].setId(j);
radioGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(radioGroup[i]);
answer[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int checkedRadioButtonId = v.getId();
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
if (checkedRadioButton.isChecked()) {
Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
}
}
});
i++;
}
Thanks!
as in log :
ArrayIndexOutOfBoundsException: length=4; index=4
Because answer Array is size of j instead of i, so move RadioButton click listener inside for loop:
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
...your code here...
answer[j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code here...
}
});
j++;
}
}

putting a pause in code to show image after image?

I am a complete beginner in android. I am stuck at a point in making an application. I have images stored in hashmap and whatever line I give it as an input is broken into separate words on basis of space and its corresponding images are fetched. But I dont want these images to show up at once but these should be shown one after the other and there should be a pause of almost one second between each image to show up. But seems like I am stuck because of my inexperience. In code where and how should I place a pause? Because when I use Thread.sleep anywhere in code, it pause only in beginning everytime.
textlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Speech.setText("You said " + matches_text.get(position));
selectedFromList = (matches_text.get(position));
String[] separated = selectedFromList.split(" ");
// ImageView iv;
final int[] imageViews = { R.id.imageView1,
R.id.imageView2, R.id.imageView3, R.id.imageView4,
R.id.imageView5, R.id.imageView6, R.id.imageView7,
R.id.imageView8, R.id.imageView9, R.id.imageView10,
R.id.imageView11, R.id.imageView12,
R.id.imageView13, R.id.imageView14,
R.id.imageView15, R.id.imageView16,
};
final_length = separated.length;
int b = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("apple",R.drawable.apple);
maps pol=new maps();
pol.map_A();
pol.map_B();
pol.map_C();
pol.map_D();
pol.map_E();
for (int i = 0; i < separated.length; i++) {
iv = (ImageView) findViewById(imageViews[i]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
100, 100);
iv.setLayoutParams(layoutParams);
if(pol.map_a.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_a.get(separated[i].toLowerCase()));
}
else if(pol.map_b.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_b.get(separated[i].toLowerCase()));
}
else if(pol.map_c.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_c.get(separated[i].toLowerCase()));
}
else if(pol.map_d.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_d.get(separated[i].toLowerCase()));
}
else if(pol.map_e.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_e.get(separated[i].toLowerCase()));
}
}}
Change your for loop as following:
Handler handler1 = new Handler();
for (int i = 0; i < separated.length; i++) {
final int iDupe = i;
handler1.postDelayed(new Runnable() {
public void run() {
iv = (ImageView) findViewById(imageViews[iDupe]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);
if(pol.map_a.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_a.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_b.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_b.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_c.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_c.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_d.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_d.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_e.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_e.get(separated[iDupe].toLowerCase()));
}
}
}, i * 1000);
}

onClickListener onclicklistener Android Java programming

When i click on the images it doesnt change the display textview, where did i go wrong?
**List<ImageView> fields = new ArrayList<ImageView>();
for(int i = 0; i < 64; i++) {
try{
id = R.id.class.getField("square" + (i+1)).getInt(0);
views.add((ImageView)findViewById(id));
((View) fields).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View fields) {
for(int i=0; i < 64; i++)
{
display = (TextView) findViewById(R.id.textView1);
display.setText("square" + i);
}
}
});
}
catch(Exception e){}
}**
}
}
It looks like you're adding the onClick listener to the ArrayList of views, not the image you added. Change
((View) fields).setOnClickListener
to
findViewById(id).setOnClickListener

Categories