ImageButton to show image of ImageView onClick - android-studio

I want an ImageButton to change its image when clicked on it. But the image that it changes to has to be the image from an ImageView. Is this possible?
EDIT:
in the first activity where you chose your character to play with, there´s an ImageView. The Image of it is being changed to the Image of the chosen character via onClickListener that is set for an ImageButton:
ImageView imgV3 = (ImageView) findViewById(R.id.imageView3);
View.OnClickListener onClickButton1 = view -> {
imgV3.setImageDrawable(
((ImageButton) view).getDrawable()
);
};
ImageButton imageButton1 = (ImageButton) findViewById(R.id.plOneChar1);
imageButton1.setOnClickListener(onClickButton);
ImageButton imageButton2 = (ImageButton) findViewById(R.id.plOneChar2);
imageButton2.setOnClickListener(onClickButton);
...
Until here everything's working just fine.
In the 2nd activity, where the two players play against each other, I need the current Image of ImageView3 (and imageView4 for the 2nd character, didn't post it above because it's the same code). this current image is what i want to be shown on several ImageButtons when clicked on them.
This is how i tried to solve it:
public class PlayActivity extends AppCompatActivity {
String random;
String pl1;
String pl2;
List<String> list;
Random rand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
String pl1 = "Player One";
String pl2 = "Player Two";
List<String> list = new ArrayList<String>();
list.add(pl1);
list.add(pl2);
Random rand = new Random();
String random = list.get(rand.nextInt(list.size()));
Toast.makeText(this, "It´s your turn: " + random, Toast.LENGTH_SHORT).show();
}
public void onClickImgBtn (View view) {
ImageButton imgBtn = (ImageButton) view;
ImageView imgV3 = (ImageView) findViewById(R.id.imageView3);
ImageView imgV4 = (ImageView) findViewById(R.id.imageView4);
if((random == pl1) && (imgBtn.getDrawable() == null)){
imgBtn.setImageDrawable(imgV3.getDrawable());
random = list.get(rand.nextInt());
} else if((random == pl2) && (imgBtn.getDrawable() == null)) {
imgBtn.setImageDrawable(imgV4.getDrawable());
random = list.get(rand.nextInt());
} else {
Toast.makeText(this,"Chose other section!", Toast.LENGTH_SHORT).show();
}
}
}
I hope this will help to find what I'm doing wrong. Let me know if more info needed.
EDIT SOLUTION:
I found a solution. I used getTag() & setTag() and global variables.
At first i created a new class MyApplication which extends Application to declare 3 global variables:
public class MyApplication extends Application {
Integer defaultTag = R.drawable.white;
Integer resImgV3;
public Integer getResImgV3() {
return resImgV3;
}
public void setResImgV3(int resImgV3) {
this.resImgV3 = resImgV3;
}
Integer resImgV4;
public Integer getResImgV4() {
return resImgV4;
}
public void setResImgV4(int resImgV4) {
this.resImgV4 = resImgV4;
}
}
Then i set an onClickListener to all ImageButtons that changes the Image of the ImageViews (imgV3 and imgV4) by getting the Tags of the ImageButtons which are set to the id of the drawable in each ImageButton and it also sets the value of the global variables resImgV3 and resImgV4 to the id of the now set drawables of imgV3 and imgV4:
ImageView imgV3 = (ImageView) findViewById(R.id.imageView3);
imgV3.setTag(R.drawable.kid1);
imgV3.setImageResource(R.drawable.kid1);
((MyApplication)this.getApplication()).setResImgV3((Integer) imgV3.getTag());
View.OnClickListener onClickButton = view -> {
imgV3.setTag((Integer) view.getTag());
imgV3.setImageResource((Integer) view.getTag());
((MyApplication) this.getApplication()).setResImgV3((Integer) imgV3.getTag());
};
ImageView imgV4 = (ImageView) findViewById(R.id.imageView4);
imgV4.setTag(R.drawable.kid2);
imgV4.setImageResource(R.drawable.kid2);
((MyApplication)this.getApplication()).setResImgV4((Integer) imgV4.getTag());
View.OnClickListener onClickButton1 = view -> {
imgV4.setTag((Integer) view.getTag());
imgV4.setImageResource((Integer) view.getTag());
((MyApplication) this.getApplication()).setResImgV4((Integer) imgV4.getTag());
};
ImageButton imageButton1 = (ImageButton) findViewById(R.id.plOneChar1);
imageButton1.setImageResource(R.drawable.kid1);
imageButton1.setTag(R.drawable.kid1);
imageButton1.setOnClickListener(onClickButton);
ImageButton imageButton2 = (ImageButton) findViewById(R.id.plOneChar2);
imageButton2.setImageResource(R.drawable.kid2);
imageButton2.setTag(R.drawable.kid2);
imageButton2.setOnClickListener(onClickButton); //and 6 more ImageButtons
And finally in the 2nd activity, where i needed the images of imageView3 and imageView4, i can easily get the resId of each drawable by just accessing the MyApplication-class like following:
ImageView imgV5 = (ImageView) findViewById(R.id.imageView5);
imgV5.setImageResource(((MyApplication) this.getApplication()).getResImgV3());
imgV5.setTag(((MyApplication) this.getApplication()).getResImgV3());
ImageView imgV6 = (ImageView) findViewById(R.id.imageView6);
imgV6.setImageResource(((MyApplication) this.getApplication()).getResImgV4());
imgV6.setTag(((MyApplication) this.getApplication()).getResImgV4());
I hope this will help other ones with the same problem in the future.

Try this:
ImageButton Demo_button = (ImageButton)findViewById(R.id.firstimage);
// when you click this demo button
Demo_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Demo_button.setImageResource(R.drawable.secondimage);
}
}

Related

how to send data from popup window to a tabbed activity having fragments?

mainActivity has button. After button is clicked a popup message show having a button and a TextInputLayout.
data is sent to a tabbed acticity having 2 fragments and
the data is shown in textview of first fragment. Error is the data wont show in the textview while running
adapter for 2 fragments--
public class adapter extends FragmentPagerAdapter {
public adapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 1) {
fragment = new SecondFragment();
} else {
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = "TextView";
} else if (position == 1) {
title = "Listview";
}
return title;
}
}
mainActivity(having popup window on clicking button)
myDialog = new Dialog(this);
}
//for for joining match
public void ShowPopup(View view) {
myDialog.setContentView(R.layout.popup);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
name = myDialog.findViewById(R.id.ig_name);
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
entry = myDialog.findViewById(R.id.entry);
entry.setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});
}
}
my firstFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
secondActivity activity = (secondActivity) getActivity();
TextView output = view.findViewById(R.id.textshow);
Bundle results = activity.getMyData();
String value1 = results.getString("value");
output.setText(value1);
return view;
}
secondActivity (intent is transfered from popup window)
public class secondActivity extends AppCompatActivity {
private String name;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new adapter(getSupportFragmentManager()));
tabLayout = findViewById(R.id.tabs_layout);
tabLayout.setupWithViewPager(viewPager);
Intent intent = getIntent();
name = intent.getExtras().getString("igname");
}
public Bundle getMyData() {
Bundle bundle = new Bundle();
bundle.putString("value", name);
return bundle;
}
}
Get the "igname" String value in onClickListner & also dismiss the dialog before finishing the activity.
entry.setOnClickListener(v -> {
String igname = Objects.requireNonNull(name.getEditText()).getText().toString();
Intent intent = new Intent(getApplicationContext(), secondActivity.class);
intent.putExtra("igname", igname);
startActivity(intent);
finish();
});

i dont know why but it crashing me at startActivity(StartIntent); i try to sand a ArrayList of the class User to ScenedActivity

the cod crash on startActivity(StartIntent);
i dont know why i start us android studio and i try code that i had in my head
and i dont know why but it crashing me at startActivity(StartIntent); i try to sand a ArrayList of the class User to ScenedActivity
ArrayList<User> users = new ArrayList<>();
User Dan = new User("dan","ali","game12",1234);
static int cod;
final int num = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
users.add(Dan);
setContentView(R.layout.activity_main);
final EditText Cod = findViewById(R.id.Cod);
Button NextActivity = findViewById(R.id.NextActivity);
NextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(Cod))//if the text box is empty pot 0 in cod
cod = Integer.parseInt(Cod.getText().toString());
else if (isEmpty(Cod))
cod = 0;
if (cod == num ) {// if the cod that pot in EditText = my cod(num) go on
Intent StartIntent = new Intent(getApplicationContext(), ScenedActivity.class);
StartIntent.putExtra("android.intent.category.LAUNCHER", "Hi");//sand to scened activity string "hi"
StartIntent.putExtra("android.intent.category.LAUNCHER1",users);//sand to scened activity ArrayList of User
startActivity(StartIntent);
}
else {
Toast.makeText(getBaseContext(),"Error worng code",Toast.LENGTH_SHORT).show();//sand
}
}
});
}
private boolean isEmpty(EditText etText) {//check if text box is empty
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
}

How to create when i click 1st item in arrayList1 will open page with 1st item in arrayList2

When I click first or second item from 1st array list I get first item from array list two, but I need if i click second item on array list 1 I get shown second item from list two
public class SecondActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> 1stArrayList;
ArrayList<String> 2ndArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
listView = (ListView) findViewById(R.id.listView);
1stArrayList = new ArrayList<>();
1stArrayList .add("A");
1stArrayList .add("B");
1stArrayList .add("C");
2ndArrayList = new ArrayList<>();
2ndArrayList.add("1");
2ndArrayList.add("2");
2ndArrayList.add("3");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item, 1stArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String 2ndArrayList= listView.getItemAtPosition(position).toString();
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList ", 2ndArrayList );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
}
}
A possible solution would be getting the value directly from the array using the position of the view clicked. Like the following:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String secListItem = secArrayList.get(position);
SharedPreferences settings = getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("2ndArrayList", secListItem );
editor.apply();
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
startActivity(intent);
}
});
But you have to be sure that both the arrays will have the same size or you may have an IndexOutOfBoundsException.
Another solution would be using some Map with the values from arraylist1 and arraylist2, implementing a custom adapter that extends BaseAdapter, populating the views with the values from the first array with getView() and using getItem() to return the values from the second list, but that's harder to do.
Also if you don't mean to persist the item and only transfer them between activities, you can use the Intent to do it. In this way:
Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
Intent.putExtra("2ndArrayList", secListItem);
startActivity(intent);
And recover in the third activity with something like:
String secArrayItem = "";
Bundle extras = getIntent().getExtras();
if (extras != null) secArrayItem = extras.getString("2ndArrayList");

dynamically adding textviews to listview item

I have this arryalist of items, each item has hour as string and string of minutes. I can split minutes to array and for each minute I want to add textview with on clicklistener.
I have implemented arrayadapter for listview. Everything works like expected but only one thing : I don't see all textviews as they are not shown properly on the end of the display.
ListView row item layout has LinearLayout and textview to show hours.
Code for listview adapter :
public class DotazAdapter extends ArrayAdapter<Hours> {
private final ArrayList<Hours> model;
private final Context context;
public DotazAdapter(Context context, ArrayList<Hours> model) {
super(context, R.layout.hours_minutes,model);
this.model=model;
this.context=context;
// TODO Auto-generated constructor stub
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = null;
row = inflater.inflate(R.layout.hours_minutes, parent,false);
LinearLayout riadok = (LinearLayout)row.findViewById(R.id.horny);
TextView hodiny = (TextView)row.findViewById(R.id.hodinyBTV);
hodiny.setText(model.get(position).getHour());
String[] minuty = model.get(position).getMinutes().split(" ");
for(int i = 0; i<minuty.length;i++){
final TextView minutka = new TextView(context);
minutka.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
minutka.setText(minuty[i]+" ");
minutka.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Stlacil si riadok "+position+ " a cislo v riadku :", Toast.LENGTH_SHORT).show();
}
});
riadok.addView(minutka, );
}
return row;
}
}
Layout for listitem :
xml version=1.0 encoding=utf-8
LinearLayout xmlnsandroid=httpschemas.android.comapkresandroid
androidid=#+idhorny
androidlayout_width=match_parent
androidlayout_height=wrap_content
TextView
androidid=#+idhodinyBTV
androidlayout_width=wrap_content
androidlayout_height=wrap_content
androidlayout_marginRight=5dp
androidbackground=#F00C0C
androidtextColor=#FFFFFF
androidtextSize=18sp
LinearLayout

Android : set visibility of individual buttons in a custom ListView

I have a ListView with a custom Adapter (extending BaseAdapter), and the layout of each row consists of a TextView and a Button. After the list is created, I want to change the visibility of specific buttons.
For this, I would need to programatically access the View of an individual row. I am not able to find out how to do it. This answer mentions getView(int position), but I can't find that method; getView() needs 3 parameters. What do I pass as convertView to getView(int position, View convertView, ViewGroup parent)?
Could you please point me in right direction?
UPDATE: The View obtained by View v = myListView.getChildAt(myListView.getFirstVisiblePosition()); is null. Also, myListView.getChildCount() is returning 0.
onItemClick will pass you the View in the ListView that was clicked. Then you can grab that View and do whatever you want with it, including changing visibility, etc.
http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
Here is an example I of a custom adapter I used in a list view in which the user can select items in the listView and mark them for Delete. The key is to add the onClickListener after you have a view. Then you can use that to not only change the view, but update the data of the adapter too.
Hopefully you can modify this code to suit your particulars.
private class DeletePlayerAdapter extends ArrayAdapter<Player> {
Context context;
int layoutResourceId;
ArrayList<Player> data;
public DeletePlayerAdapter(Context context, int layout,
ArrayList<Player> list) {
super(context, layout, list);
this.layoutResourceId = layout;
this.context = context;
this.data = list;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = convertView;
PlayerHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PlayerHolder();
holder.player_name = (TextView) row
.findViewById(R.id.player_name);
holder.player_number = (TextView) row
.findViewById(R.id.player_number);
holder.seeded_button = (ImageButton) row
.findViewById(R.id.delete_toggle);
holder.player_name.setTypeface(tf);
holder.player_number.setTypeface(tf);
row.setTag(holder);
players_array.get(position).marked_for_delete = false;
} else {
Log.d("PLAYER_ADAPTER", "NOT_NULL ROW");
holder = (PlayerHolder) row.getTag();
}
holder.seeded_button.setOnClickListener(new OnClickListener() {
private int pos = position;
public void onClick(View v) {
ImageButton b = (ImageButton) v;
if (b.isSelected()) {
b.setSelected(false);
players_array.get(pos).marked_for_delete = false;
} else {
b.setSelected(true);
players_array.get(pos).marked_for_delete = true;
}
}
});
Player p = data.get(position);
holder.player_name.setText(p.name);
holder.player_number.setText(String.valueOf(position+1));
holder.seeded_button
.setSelected(players_array.get(position).marked_for_delete);
return row;
}
}
static class PlayerHolder {
TextView player_number;
TextView player_name;
ImageButton seeded_button;
}

Resources