Change imageButton resource in dynamic listview - android

I have this piece of code:
public void ON_function(View view) {
int position = lv.getPositionForView(view);
String pozycja = Integer.toString(position);
String tile_content = listaurzadzen.get(position).toString().replace("{urzadzenie=", "\0").replace("}", "\0");
String[] IP_substring = tile_content.split("\r\n");
SendMessage(IP_substring[1].trim(), "switchon");
//ImageButton bulb = (ImageButton)findViewById(R.id.imageButton);
//bulb.setImageResource(R.drawable.bulb_on);
}
public void OFF_function(View view) {
int position = lv.getPositionForView(view);
String pozycja = Integer.toString(position);
String tile_content = listaurzadzen.get(position).toString().replace("{urzadzenie=", "\0").replace("}", "\0");
String[] IP_substring = tile_content.split("\r\n");
SendMessage(IP_substring[1].trim(), "switchoff");
//ImageButton bulb = (ImageButton)findViewById(R.id.imageButton);
//bulb.setImageResource(R.drawable.bulb_off);
}
Two simple functions which are called from dynamically created listview rows, each sends a message or whatever.
My problem is, if I can get the position using (view) to get the string of specific row, why can't I use it to change the image button resource of this specific row? Do I really have to create all these getView methods to make it happen? If so how do I do it with a simple adapter. I have been looking for a solution for a long time.

Can you do
ImageButton bulb = (ImageButton) view.findViewById(R.id.imageButton);
bulb.setImageResource(R.drawable.bulb_off);

Related

How to add an image to a random ImageView in Android Studio?

I am creating a ticTacToe app, and when I click on some ImageView, I set resource of that ImageView to a specific resource(X image). Now, the problem is I want to set "O" image to some other random ImageView,
public void imageViewClicked(View view) {
ImageView counter = (ImageView) view;
counter.setImageResource(R.drawable.x);
}
Keep IDs of all avaliable ImageViews in single collection in your activity:
private List<Integer> images = new ArrayList<>();
onCreate() {
images.add(R.id.image1);
images.add(R.id.image2);
//..
}
When user clicks on some ImageView, remove it from the mentioned collection, then select random view from the rest and set resource:
onClick(View view) {
images.remove(view.getId());
int rnd = new Random().nextInt(images.size() - 1);
int id = images.get(rnd);
findViewById(id).setImageResource(R.drawable.o);
images.remove(rnd);
}
Hope it helps.
You can storage your drawable resource in a variable and manage it by turn (after each play).
First turn mydrawableResource = R.drawable.x.
Second turn mydrawableResource = R.drawable.o.
Then you set:
public void imageViewClicked(View view) {
ImageView counter = (ImageView) view;
counter.setImageResource(mydrawableResource );
}

how change changed textview android

I passed the data from the first actvity (like int VNIMANI and int OBRATNOST). This data set my TextView after I came on second activity. now I need a button. And when I click on the button I need increment +1. But the code doesn't work.
TextView tvPaklic = (TextView) findViewById(R.id.paklic);
String paklic = String.valueOf( + 10+ (VNIMANI+OBRATNOST));
tvPaklic.setText(paklic);
}
int newPaklic = 0;
public void plusPaklic (View v){
newPaklic = newPaklic + 1;
displayPaklicDve (newPaklic);
}
private void displayPaklicDve(int newPaklic) {
TextView tvpaklicdve = (TextView) findViewById(R.id.paklic);
String paklicdve = String.valueOf(newPaklic);
tvpaklicdve.setText(paklicdve);
}
I would really like to suggest you refer this one Read this, will solve your problem
You were used 2 Textview objects with referring one id check that.
TextView tvPaklic = (TextView) findViewById(R.id.paklic);
TextView tvpaklicdve = (TextView) findViewById(R.id.paklic);

Randomly select one of two ImageViews and update ResourceImage

I have created in my layout two ImageViews, let's call them imageviewTop and imageviewBottom.
I saved two images into the drawable (green_image.png and red_image.png).
I also added a button and want I would like to do is, when the button is clicked, one of the ImageViews will get selected randomly and from the green_image it will change to the red_image.
I already tried with creating a switch/case statement and generating a random number, like 1 or 2.
Based on this number the case statement would update either the top or bottom image.
This is working fine for 2 ImageViews, but in case I would have 100, I would need to create 100 cases in code.
I am searching for a more dynamic option.
I know how to update the image for the ImageView, I am struggling with the part, on how to select one ImageView randomly, if it is possible.
Here is the code:
public class MainActivity extends Activity {
ImageView imagevieTop, imageviewBottom;
Button randomButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagevieTop = (ImageView) findViewById(R.id.imageViewTop);
imageviewBottom = (ImageView) findViewById(R.id.imageViewBottom);
randomButton = (Button) findViewById(R.id.buttonRandom);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// randomly select one of the two imageviews
// for example: randomly selected imageviewTop
// set imageresource red_image to imageviewTop
//at next start up it would select either top or bottom, 50%-50% and then assign the image to it
}
});
}
}
You could just use one ImageView, and randomize the picture you draw.
Alternatively, you could adjust this to use an array of ImageViews. Your choice.
The line you want, though, is int index = random.nextInt(imgs.length); to get a random index from the list.
public class MainActivity extends Activity {
int[] imgs = new int[] { R.drawable.green_image, R.drawable.red_image };
Button randomButton;
private final Random random = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imgView = (ImageView) findViewById(R.id.imageView);
randomButton = (Button) findViewById(R.id.buttonRandom);
randomButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index = random.nextInt(imgs.length);
// randomly select one of the two drawables
int resId = imgs[index];
// set imageresource imgView
Drawable d = getResources().getDrawable(resId);
imgView.setImageDrawable(d);
}
});
}
}
To handle the "100 ImageViews" problem, I'd recommend not copying 100 lines of code, and instead looping over reasonable ID values.
List<ImageView> imgViews = new ArrayList<ImageView>();
for (int i = 0; i < 100; i++) {
int resId = getResources().getIdentifier("imgView" + i, "id", getPackageName());
ImageView nextImg = (ImageView) findViewById(resId);
imgViews.add(nextImg);
}
In case you want to do a dynamic selection of "n" ImageView elements, then you'll need to store them in a data structure (e.g. an array, a list, etc.). For example this code will select a random ImageView from a list:
public ImageView getRandomImageView(final List<ImageView> imageViewList) {
final Random random = new Random();
//The "nextInt" method works in the half-open range [0, n), so it'll never be equal to the list size.
final int randomElement = random.nextInt(imageViewList.size());
return imageViewList.get(randomElement);
}
In your case, with two ImageView's ("imagevieTop" and "imageviewBottom") declared in fixed variables then you would need to pass them to a list or something similar in order to select one of them dynamically.

TextView not showing up in other activity

I have been able to pass data to other activities except this one. Can anyone see what I'm doing wrong. The only error i'm getting is that my TextView showmsg is NOT showing up in the new activity. Does anyone know why?
public class MyScanActivity extends Activity
{
private static final String MY_CARDIO_APP_TOKEN = "NOT THE PROBLEM";
final String TAG = getClass().getName();
private Button scanButton;
private TextView resultTextView;
private Button buttonBack;
private TextView showmsg;
private int MY_SCAN_REQUEST_CODE = 100; // arbitrary int
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myscan);
Intent in = getIntent();
if (in.getCharSequenceExtra("usr") != null) {
final TextView setmsg = (TextView)findViewById(R.id.showmsg);
setmsg.setText(in.getCharSequenceExtra("usr"));
}
resultTextView = (TextView)findViewById(R.id.resultTextView);
scanButton = (Button)findViewById(R.id.scanButton);
buttonBack = (Button)findViewById(R.id.buttonBack);
showmsg = (TextView) findViewById(R.id.showmsg);
There are not too many options for how your text can be not shown.
You have the view itself messed up: Check this by putting some sample text in the XML file using android:text="TEST" in the TextView showmsg. Your text should appear, unless your text is the wrong color or size, or something else happens to be above it.
You aren't actually finding it with findViewById() (I hope you've double checked that in a debugger) I agree with alex that you might not want R.id.showmsg. Did you mean to put R.id.resultTextView there instead?
Your passed text is not actually coming through. You should do a log statement, like Log.v(TAG, "Passed text is " + in.getCharSequenceExtra("urs")); and make sure the text is actually coming through.
I haven't test it. but i think that is the reason.
change here:
if (in.getCharSequenceExtra("usr") != null) {
final TextView setmsg = (TextView)findViewById(R.id.showmsg);
setmsg.setText(in.getCharSequenceExtra("usr"));
}
with this:
showmsg = (TextView) findViewById(R.id.showmsg);
if (in.getCharSequenceExtra("usr") != null) {
showmsg.setText(in.getCharSequenceExtra("usr"));
}

How to get particular info about a button inside a viewflipper view on android?

I try to make an aplication that use a viewFlipper to flip some text.
The content is populated from a cursor and views are added programaticaly.
Each view is based on the same xml layout file and each of the views contain 2 buttons.
When I press one button I fire onClick event, but how can I pass a custom variable to the onclick event?
I have a var id witch I need to be different for each view and I need to get this value on button press.
Here is my code:
Cursor cur = db.rawQuery(
"SELECT * FROM items WHERE id_cat = " + id_cat + "", null);
TextView t = new TextView(this);
int total_items = cur.getCount();
if (cur.moveToFirst()) {
do {
String data = cur.getString(cur.getColumnIndex("item_text"));
String item_id= cur.getString(cur.getColumnIndex("_id"));
int current = cur.getPosition()+1;
// load xml template
LayoutInflater inflater = LayoutInflater.from(this);
View v = inflater.inflate(R.layout.item_flip, null, false);
ToggleButton btnf=(ToggleButton)v.findViewById(R.id.favorite);
btnf.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch(v.getId()){
case R.id.favorit:
// switch favorite
SQLiteDatabase db = dbAdapter.openDataBase();
if(status==1) {
//// HERE I NEED THE ITEM_ID DISTINCT FOR EACH VIEW
db.execSQL("UPDATE items SET favorite = 0 WHERE items._id = " + item_id);
} else {
db.execSQL("UPDATE items SET favorite = 1 WHERE items._id = " + item_id);
}
System.out.println("Switch");
db.close();
break;
}
}
});
vf.addView(v);
} while (cur.moveToNext());
The button works ok but the item ID is not passed.
If I have 5 items in my viewflipper, item_id will become 1, then 2, then 3, then .... then 5
and no mather whiitch of the buttons I press the item_id will be the id of the last view.
Thanks in advance if u have any solution.
OMG,
is the 3rd time when I post a question here and in next 10 minutes I fine the solution by myself :)
he is the solution if anyone need something similar:
In my XML I added a tag:
<ToggleButton
android:id="#+id/favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/share"
android:layout_marginTop="6dip"
android:textOn="Favorit"
android:textOff="Favorit"
android:text="Favorit"
android:tag="999" />
then when I build the specified view I modify the tag on each separated view with my item_id:
ToggleButton swc_favorite = (ToggleButton) v.findViewById(R.id.favorite);
if(status==1) {
swc_favorit.setChecked(true);
} else {
swc_favorit.setChecked(false);
}
// set favorit tag
swc_favorit.setTag(item_id);
Next in the clicklistener I get that tag from the clicked view :
final ToggleButton btnf=(ToggleButton)v.findViewById(R.id.favorite);
btnf.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String item_id_clicked = (String) btnf.getTag();
........
Need to set ToggleButton btnf as final to work.
Thanks and hope to be a help for some of you.

Categories

Resources