Android remove custom view from tablayout tab - android

I am currently working on tab layout. Almost i have done it.
My scenario is at my 0 position i have used custom view which includes imageview and textview.
My first tab at 0 position have some conditions. Which they are
1) At 0 index fragment i am calling API. so if there is no data then display no data available and tab layout simply shows a icon.
2) After if user wants to add data from button click then from new acttiviy he can fill the data and icon at 0 position of tablayout should be changed and textview will be displayed with selected date.
Problem :
If i call setUpTabIcons() method in onResume() method then imageview icons are repeated.
Here is screenshot.
Here is my code.
private void setupTabIcons() {
if (mediaPrefs.getString(Constant.SharedPreferences_wedding_id, "").length() > 0) {
List<EventData> eventData = appDatabase.eventListDao().getSelectedWeddingEvents(Integer.parseInt(mediaPrefs.getString(Constant.SharedPreferences_wedding_id, "0")));
View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab_event_date_view, null);
TextView txt_day = (TextView) view.findViewById(R.id.txt_day);
TextView txt_month = (TextView) view.findViewById(R.id.txt_month);
ImageView img_event = (ImageView)view.findViewById(R.id.img_icon_events);
if (eventData != null && eventData.size() > 0) {
if (eventData.get(0).getEventdate().length() > 0) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat day_format = new SimpleDateFormat("dd");
DateFormat month_format = new SimpleDateFormat("MMM");
Date date_day = null, date_month = null;
try {
date_day = simpleDateFormat.parse(eventData.get(0).getEventdate());
date_month = simpleDateFormat.parse(eventData.get(0).getEventdate());
String day = day_format.format(date_day);
String month = month_format.format(date_month);
txt_day.setText(day);
txt_month.setText(month);
img_event.setVisibility(View.GONE);
txt_day.setVisibility(View.VISIBLE);
txt_month.setVisibility(View.VISIBLE);
Log.v("asfasf","heree2");
tabs.getTabAt(0).setCustomView(view);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
Log.v("asfasf","heree1");
img_event.setVisibility(View.VISIBLE);
txt_day.setVisibility(View.GONE);
txt_month.setVisibility(View.GONE);
img_event.setImageResource(R.mipmap.host_add_event_small);
tabs.getTabAt(0).setCustomView(view);
}
} else {
Log.v("asfasf","heree");
img_event.setVisibility(View.VISIBLE);
txt_day.setVisibility(View.GONE);
txt_month.setVisibility(View.GONE);
img_event.setImageResource(R.mipmap.host_add_event_small);
tabs.getTabAt(0).setCustomView(view);
}
}
tabs.getTabAt(1).setIcon(R.mipmap.camera_icon);
tabs.getTabAt(2).setIcon(R.mipmap.chat_icon);
tabs.getTabAt(3).setIcon(R.mipmap.notification_icon);
tabs.getTabAt(4).setIcon(R.mipmap.chat_userprofile_light);
tabs.setRotationX(180);
LinearLayout tabListed = ((LinearLayout) tabs.getChildAt(0));
for (int position = 0; position < tabListed.getChildCount(); position++) {
LinearLayout item = ((LinearLayout) tabListed.getChildAt(position));
item.setRotationX(180);
}
tabs.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(view_pager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
if (tab.getPosition() == 0) {
View tabView = tab.getCustomView();
TextView txt_day = (TextView) tabView.findViewById(R.id.txt_day);
TextView txt_month = (TextView) tabView.findViewById(R.id.txt_month);
if(txt_day.getText().toString().trim().length()>0 && txt_month.getText().toString().trim().length()>0){
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.dark_gray_wedding);
txt_day.setTextColor(tabIconColor);
txt_month.setTextColor(tabIconColor);
}else{
ImageView img_event = (ImageView)tabView.findViewById(R.id.img_icon_events);
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.dark_gray_wedding);
if(img_event!=null){
img_event.setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
} else {
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.dark_gray_wedding);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
if (tab.getPosition() == 0) {
TextView txt_day = (TextView) tab.getCustomView().findViewById(R.id.txt_day);
TextView txt_month = (TextView) tab.getCustomView().findViewById(R.id.txt_month);
if(txt_day.getText().toString().trim().length()>0 && txt_month.getText().toString().trim().length()>0){
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.light_gray_wedding);
txt_day.setTextColor(tabIconColor);
txt_month.setTextColor(tabIconColor);
}else{
ImageView img_event = (ImageView)tab.getCustomView().findViewById(R.id.img_icon_events);
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.light_gray_wedding);
if(img_event!=null){
img_event.setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
} else {
int tabIconColor = ContextCompat.getColor(getActivity(), R.color.light_gray_wedding);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
super.onTabReselected(tab);
}
});
}

In order to remove a custom view from a tab layout you just need to set the custom view for that tab to null. Here's an example in Java:
tabs.getTabAt(0).setCustomView(null);
and Kotlin:
tabs.getTabAt(0)?.customView = null

TextView txt_day =(TextView)tabs.getTabAt(0).getCustomView().findViewById(R.id.txt_day);
TextView txt_month =(TextView)tabs.getTabAt(0).getCustomView().findViewById(R.id.txt_month);
txt_day.setText("");
txt_month.setText("");
#Piyush You can find the textview of the custom tab then set textview blank

Related

RecyclerView Doesn't Reload Code When Reopening Item

When I first start up my app and the user clicks on an item in a recyclerview, everything initializes as expected.
When the user hits the back button to go back to the main item list page and then clicks on the same or another item, the page is not loaded the same.
My initial layout is the same as the second image without the location name and coordinates updated.
What frustrates me is the day names are initialized in the same exact method. I have debugged it in many ways and have found that the code must not be run - the code inside of it has NO affect on the outcome of the item's detail page when it is reloaded. This code only affects the actual layout the FIRST time it is run and has no affect any other time.
RecyclerView Adapter:
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<LocationContent.LocationItem> mValues;
public SimpleItemRecyclerViewAdapter(List<LocationContent.LocationItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public LocationContent.LocationItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
Code that is supposed to be run:
Log.i("LOAD DATA", "Called");
Log.e("SWITCH CASE (IDF)", AssetLoader.getMondayName(mItem.id));
// To layout below the textView to avoid crashes
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, R.id.textView);
switch(AssetLoader.getLastItemDayName(mItem.id)) {
case "Sun":
sunday.setLayoutParams(p);
break;
case "Mon":
monday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Tues":
tuesday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Wed":
wednesday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Thurs":
thursday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Fri":
friday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "Sat":
saturday.setLayoutParams(p);
// Make sunday layout before monday (as its default is below textView)
p.removeRule(RelativeLayout.BELOW);
p.addRule(RelativeLayout.BELOW, R.id.monday);
sunday.setLayoutParams(p);
break;
case "":
sunday.setLayoutParams(p);
break;
}
Log.e("MONDAY NAME EDIT()", AssetLoader.getMondayName(mItem.id));
if (!AssetLoader.dataInMonday(mItem.id)/*AssetLoader.getMondayName(mItem.id).equals("") || AssetLoader.getMondayName(mItem.id).equals("Monday:")*/) {
monday.setVisibility(View.GONE);
monday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsMonday(mItem.id, "");
} else {
monday.setVisibility(View.VISIBLE);
monday_detail.setVisibility(View.VISIBLE);
monday.setText(AssetLoader.getMondayName(mItem.id));
if(AssetLoader.getItemDetailsMonday(mItem.id).equals("")) {
monday_detail.setText(R.string.no_data);
} else {
monday_detail.setText(AssetLoader.getItemDetailsMonday(mItem.id));
}
}
if (!AssetLoader.dataInTuesday(mItem.id)/*AssetLoader.getTuesdayName(mItem.id).equals("") || AssetLoader.getTuesdayName(mItem.id).equals("Tuesday:")*/) {
tuesday.setVisibility(View.GONE);
tuesday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsTuesday(mItem.id, "");
} else {
tuesday.setVisibility(View.VISIBLE);
tuesday_detail.setVisibility(View.VISIBLE);
tuesday.setText(AssetLoader.getTuesdayName(mItem.id));
if(AssetLoader.getItemDetailsMonday(mItem.id).equals("")) {
tuesday_detail.setText(R.string.no_data);
} else {
tuesday_detail.setText(AssetLoader.getItemDetailsTuesday(mItem.id));
}
}
if (!AssetLoader.dataInWednesday(mItem.id)/*AssetLoader.getWednesdayName(mItem.id).equals("") || AssetLoader.getWednesdayName(mItem.id).equals("Wednesday:")*/) {
wednesday.setVisibility(View.GONE);
wednesday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsWednesday(mItem.id, "");
} else {
wednesday.setVisibility(View.VISIBLE);
wednesday_detail.setVisibility(View.VISIBLE);
wednesday.setText(AssetLoader.getWednesdayName(mItem.id));
if(AssetLoader.getItemDetailsWednesday(mItem.id).equals("")) {
wednesday_detail.setText(R.string.no_data);
} else {
wednesday_detail.setText(AssetLoader.getItemDetailsWednesday(mItem.id));
}
}
if (!AssetLoader.dataInThursday(mItem.id)/*AssetLoader.getThursdayName(mItem.id).equals("") || AssetLoader.getThursdayName(mItem.id).equals("Thursday:")*/) {
thursday.setVisibility(View.GONE);
thursday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsThursday(mItem.id, "");
} else {
thursday.setVisibility(View.VISIBLE);
thursday_detail.setVisibility(View.VISIBLE);
thursday.setText(AssetLoader.getThursdayName(mItem.id));
if(AssetLoader.getItemDetailsThursday(mItem.id).equals("")) {
thursday_detail.setText(R.string.no_data);
} else {
thursday_detail.setText(AssetLoader.getItemDetailsThursday(mItem.id));
}
}
if (!AssetLoader.dataInFriday(mItem.id)/*AssetLoader.getFridayName(mItem.id).equals("") || AssetLoader.getFridayName(mItem.id).equals("Friday:")*/) {
friday.setVisibility(View.GONE);
friday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsFriday(mItem.id, "");
} else {
friday.setVisibility(View.VISIBLE);
friday_detail.setVisibility(View.VISIBLE);
friday.setText(AssetLoader.getFridayName(mItem.id));
if(AssetLoader.getItemDetailsFriday(mItem.id).equals("")) {
friday_detail.setText(R.string.no_data);
} else {
friday_detail.setText(AssetLoader.getItemDetailsFriday(mItem.id));
}
}
if (!AssetLoader.dataInSaturday(mItem.id)/*AssetLoader.getSaturdayName(mItem.id).equals("") || AssetLoader.getSaturdayName(mItem.id).equals("Saturday:")*/) {
saturday.setVisibility(View.GONE);
saturday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsSaturday(mItem.id, "");
} else {
saturday.setVisibility(View.VISIBLE);
saturday_detail.setVisibility(View.VISIBLE);
saturday.setText(AssetLoader.getSaturdayName(mItem.id));
if(AssetLoader.getItemDetailsSaturday(mItem.id).equals("")) {
saturday_detail.setText(R.string.no_data);
} else {
saturday_detail.setText(AssetLoader.getItemDetailsSaturday(mItem.id));
}
}
if (!AssetLoader.dataInSunday(mItem.id)/*AssetLoader.getSundayName(mItem.id).equals("") || AssetLoader.getSundayName(mItem.id).equals("Sunday:")*/) {
sunday.setVisibility(View.GONE);
sunday_detail.setVisibility(View.GONE);
AssetLoader.setItemDetailsSunday(mItem.id, "");
} else {
sunday.setVisibility(View.VISIBLE);
sunday_detail.setVisibility(View.VISIBLE);
sunday.setText(AssetLoader.getSundayName(mItem.id));
if(AssetLoader.getItemDetailsSunday(mItem.id).equals("")) {
sunday_detail.setText(R.string.no_data);
} else {
sunday_detail.setText(AssetLoader.getItemDetailsSunday(mItem.id));
}
}
Please note that the Log.e and Log.i calls are not even being displayed in logcat/Android Monitor when the app is run. THE CODE IS BEING CALLED WHEN THE REST OF THE USER INTERFACE IS BEING CALLED! Thanks for any information you may have!
Set your adapter for RecyclerView inside onResume method.
Well I found the problem. When the DetailView for my Item was loading the first time, my variables for monday, tuesday, etc were null so they were set to the TextViews on the current layout. When the back button was pressed, these variables were no longer null but still pointed to the previous layout's variables.
Incorrect Code:
if(monday == null) {
monday = (TextView) rootView.findViewById(R.id.monday);
tuesday = (TextView) rootView.findViewById(R.id.tuesday);
wednesday = (TextView) rootView.findViewById(R.id.wednesday);
thursday = (TextView) rootView.findViewById(R.id.thursday);
friday = (TextView) rootView.findViewById(R.id.friday);
saturday = (TextView) rootView.findViewById(R.id.saturday);
sunday = (TextView) rootView.findViewById(R.id.sunday);
}
if(monday_detail == null) {
monday_detail = (TextView) rootView.findViewById(R.id.monday_detail);
tuesday_detail = (TextView) rootView.findViewById(R.id.tuesday_detail);
wednesday_detail = (TextView) rootView.findViewById(R.id.wednesday_detail);
thursday_detail = (TextView) rootView.findViewById(R.id.thursday_detail);
friday_detail = (TextView) rootView.findViewById(R.id.friday_detail);
saturday_detail = (TextView) rootView.findViewById(R.id.saturday_detail);
sunday_detail = (TextView) rootView.findViewById(R.id.sunday_detail);
}
Correct Code (Without null checks):
monday = (TextView) rootView.findViewById(R.id.monday);
tuesday = (TextView) rootView.findViewById(R.id.tuesday);
wednesday = (TextView) rootView.findViewById(R.id.wednesday);
thursday = (TextView) rootView.findViewById(R.id.thursday);
friday = (TextView) rootView.findViewById(R.id.friday);
saturday = (TextView) rootView.findViewById(R.id.saturday);
sunday = (TextView) rootView.findViewById(R.id.sunday);
monday_detail = (TextView) rootView.findViewById(R.id.monday_detail);
tuesday_detail = (TextView) rootView.findViewById(R.id.tuesday_detail);
wednesday_detail = (TextView) rootView.findViewById(R.id.wednesday_detail);
thursday_detail = (TextView) rootView.findViewById(R.id.thursday_detail);
friday_detail = (TextView) rootView.findViewById(R.id.friday_detail);
saturday_detail = (TextView) rootView.findViewById(R.id.saturday_detail);
sunday_detail = (TextView) rootView.findViewById(R.id.sunday_detail);
So by removing the null checks, my code is all initialized correctly every time and has no errors.

set background color for imageview doesn't work

I am trying to change ImageView background when clicked(like Duolingo)
Here is my code from fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.frag_repeat, container, false);
final int[] a1 = {0};
final int[] a2 = {0};
final int[] a3 = {0};
final int[] a4 = {0};
TypedArray itemsIcon = getResources().obtainTypedArray(R.array.nav_drawer_icons);
ImageView wer1 = (ImageView) rootView.findViewById(R.id.imageView);
ImageView wer2 = (ImageView) rootView.findViewById(R.id.imageView2);
ImageView wer3 = (ImageView) rootView.findViewById(R.id.imageView23);
ImageView wer4 = (ImageView) rootView.findViewById(R.id.imageView43);
TextView textView1 = (TextView) rootView.findViewById(R.id.textView711);
textView1.setText(ss[i]);
wer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a1[0] = 1;
a2[0] = 0;
a3[0] = 0;
a4[0] = 0;
}
});
wer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a2[0] = 1;
a1[0] = 0;
a3[0] = 0;
a4[0] = 0;
}
});
wer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a3[0] = 1;
a2[0] = 0;
a1[0] = 0;
a4[0] = 0;
}
});
wer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a4[0] = 1;
a2[0] = 0;
a3[0] = 0;
a1[0] = 0;
}
});
if(a1[0] > 0){
wer3.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer1.setBackgroundColor(Color.parseColor("#42A5F5"));
wer4.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else if(a2[0] > 0){
wer1.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer3.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#42A5F5"));
wer4.setBackgroundColor(Color.parseColor("#FFFFFF"));
}else if(a3[0] > 0){
wer1.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer3.setBackgroundColor(Color.parseColor("#42A5F5"));
wer4.setBackgroundColor(Color.parseColor("#FFFFFF"));
} else if(a4[0] > 0){
wer1.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer2.setBackgroundColor(Color.parseColor("#FFFFFF"));
wer4.setBackgroundColor(Color.parseColor("#42A5F5"));
wer3.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
if(i1 == 1){
wer1.setImageResource(itemsIcon.getResourceId(i, -1));
} else if(i1 == 2){
wer2.setImageResource(itemsIcon.getResourceId(i, -1));
} else if(i1 == 3){
wer3.setImageResource(itemsIcon.getResourceId(i, -1));
} else if(i1 == 4){
wer4.setImageResource(itemsIcon.getResourceId(i, -1));
}
return rootView;
}
But ImageView background doesn't change! I have CardViews inside RelativeLayout and inside RelativeLayout I have ImageView.
Please share xml file. Maybe you don't set background for ImageView in xml
Each of your onClick listeners is just toggling values in an array. I suspect what you really want is to invoke the setBackground color code inside each handler.
From your code, I think what you are trying to do is this:
Whichever button was clicked - change it's background color from white to #42A5F5.
For the other three buttons not clicked, change the background color back to white.
I don't know what the name of your class is (I'll refer to it as "YourClass"). But make your 4 ImageViews member variables.
class YourClass extends Fragment // I'm guessing this is the declaration, it doesn't matter - use whatever you have now
{
ImageView _wer1;
ImageView _wer2;
ImageView _wer3;
ImageView _wer4;
Then inside onCreateView, assign each one of these member variables exactly where you assign the local variables:
_wer1 = (ImageView) rootView.findViewById(R.id.imageView);
_wer2 = (ImageView) rootView.findViewById(R.id.imageView2);
_wer3 = (ImageView) rootView.findViewById(R.id.imageView23);
_wer4 = (ImageView) rootView.findViewById(R.id.imageView43);
Now set each of your click listeners to invoke a "ToggleBackgroundColors". Notice that there's a different index value passed to this function in each callback handler.
_wer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(0);
}
});
_wer2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(1);
}
});
_wer3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(2);
}
});
_wer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourClass.this.ToggleBackgroundColors(3);
}
});
Then implement ToggleBackgroundColors:
void ToggleBackgroundColors(int which)
{
int highlight = Color.parseColor("#42A5F5");
ImageView [] views = {_wer1, _wer2, _wer3, _wer4};
for (int x = 0; x < views.length; x++)
{
int background = (which == x) ? highlight : Color.WHITE;
views[x].setBackgroundColor(background);
}
}
In your onClickListener, you can also set colorFilter on your imageView when you onClick it.
Consider using the onTouchListener instead though as you would like the imageView to change color when you touch the button and not when you click on it.
ImageView iv = (ImageView)findViewById(resIdOfImageToFilter);
iv.setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

How to iterate through a set of buttons in Android Studio?

I'm trying to make my first app which has a set of 15 buttons. when you press a button the color changes between two numbers.Then if you press a specificity different "commit" button the buttons won't change colors any more.
My question right now is how would I be able to iterate through the buttons on the screen? I believe I need a assign the buttons a "name", "type", or something like it, and then find all instances where that happens but I cannot find the relevant getter/setter methods.
Here is my code so far:
public void clickHandler(View view) {
Button btn = (Button) view;
int id = btn.getId();
boolean clicked = isChosen(btn);
if( clicked == true && id != 1) {
btn.setBackgroundColor(-3355444);
}
else{
btn.setBackgroundColor(-16777216);
}
}
public boolean isChosen(Button btn){
ColorDrawable buttonColor = (ColorDrawable) btn.getBackground();
int colorId = buttonColor.getColor();
if(colorId == -16777216){
return true;
}
else return false;
}
public boolean player = true;
public void changeTurn(View view) {
TextView t = (TextView) findViewById(R.id.textView3);
if(player == false) {
t.setText("Player 2's turn");
player = true;
}
else{
t.setText("Player 1's turn");
player = false;
}
Hope this piece of code helps
final int buttonCount = 15;
LinearLayout mLayout = (LinearLayout) findViewById(R.id.pager);
for (int i = 0; i < buttonCount; i++) {
TextView textView = new TextView(this);
textView.setTag(String.valueOf(i));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonID = Integer.valueOf(view.getTag().toString());
updateColorForButtonAtPosition(buttonCount);
}
});
mLayout.addView(textView);
}
private void updateColorForButtonAtPosition (int buttonCount){
// add your functionality here
}

Recyclerview, I can't get item view with getChildAt(position). Null object reference

I am using a recyclerView inside my navigation drawer and I am using this library Twoway-view to get click and selection support.
It works perfectly and I can change the color of the text and the icons without problems inside OnClick method for each position:
itemClickSupport.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClick(RecyclerView parent, View view, int position, long id) {
TypedValue typedValue = new TypedValue();
MainActivity.this.getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
final int color = typedValue.data;
//TODO Icon and text colors
for (int i = 0; i < drawerTitles.length; i++){
if (i == position){
ImageView imageViewDrawerIcon = (ImageView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.imageViewDrawerIcon);
TextView textViewDrawerTitle = (TextView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle);
imageViewDrawerIcon.setColorFilter(color);
if(Build.VERSION.SDK_INT > 15){
imageViewDrawerIcon.setImageAlpha(255);
}else{
imageViewDrawerIcon.setAlpha(255);
}
textViewDrawerTitle.setTextColor(color);
RelativeLayout relativeLayoutDrawerItem = (RelativeLayout) recyclerViewDrawer.getChildAt(i).findViewById(R.id.relativeLayoutDrawerItem);
relativeLayoutDrawerItem.setFocusableInTouchMode(true);
}else{
ImageView imageViewDrawerIcon = (ImageView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.imageViewDrawerIcon);
TextView textViewDrawerTitle = (TextView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle);
imageViewDrawerIcon.setColorFilter(getResources().getColor(R.color.md_text));
if(Build.VERSION.SDK_INT > 15){
imageViewDrawerIcon.setImageAlpha(138);
}else{
imageViewDrawerIcon.setAlpha(138);
}
textViewDrawerTitle.setTextColor(getResources().getColor(R.color.md_text));
RelativeLayout relativeLayoutDrawerItem = (RelativeLayout) recyclerViewDrawer.getChildAt(i).findViewById(R.id.relativeLayoutDrawerItem);
relativeLayoutDrawerItem.setFocusableInTouchMode(false);
}
}
//TODO Fragments (closedrawers before setfragment)
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after some time
}
}, 250);
mDrawerLayout.closeDrawers();
}
});
The problem is that I want to access to the first item like in that method, but before it (to set the first item selected, with different color, etc).
But I get a crash (null reference) when I try to get the first item outside OnClick method:
ImageView imageViewDrawerIcon = (ImageView) recyclerViewDrawer.getChildAt(0).findViewById(R.id.imageViewDrawerIcon);
All code:
// Setup RecyclerView inside drawer
recyclerViewDrawer = (RecyclerView) findViewById(R.id.recyclerViewDrawer);
recyclerViewDrawer.setHasFixedSize(true);
recyclerViewDrawer.setLayoutManager(new LinearLayoutManager(MainActivity.this));
ArrayList<DrawerItem> drawerItems = new ArrayList<>();
final String[] drawerTitles = getResources().getStringArray(R.array.drawer);
final TypedArray drawerIcons = getResources().obtainTypedArray(R.array.drawerIcons);
for (int i = 0; i < drawerTitles.length; i++) {
drawerItems.add(new DrawerItem(drawerTitles[i], drawerIcons.getDrawable(i)));
}
drawerIcons.recycle();
adapterDrawer = new DrawerAdapter(drawerItems);
recyclerViewDrawer.setAdapter(adapterDrawer);
// Here is the problem
ImageView imageViewDrawerIcon2 = (ImageView) recyclerViewDrawer.getChildAt(0).findViewById(R.id.imageViewDrawerIcon);
// RecyclerView item listener.
ItemClickSupport itemClickSupport = ItemClickSupport.addTo(recyclerViewDrawer);
itemClickSupport.setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClick(RecyclerView parent, View view, int position, long id) {
TypedValue typedValue = new TypedValue();
MainActivity.this.getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true);
final int color = typedValue.data;
//TODO Icon and text colors
for (int i = 0; i < drawerTitles.length; i++){
if (i == position){
ImageView imageViewDrawerIcon = (ImageView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.imageViewDrawerIcon);
TextView textViewDrawerTitle = (TextView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle);
imageViewDrawerIcon.setColorFilter(color);
if(Build.VERSION.SDK_INT > 15){
imageViewDrawerIcon.setImageAlpha(255);
}else{
imageViewDrawerIcon.setAlpha(255);
}
textViewDrawerTitle.setTextColor(color);
RelativeLayout relativeLayoutDrawerItem = (RelativeLayout) recyclerViewDrawer.getChildAt(i).findViewById(R.id.relativeLayoutDrawerItem);
relativeLayoutDrawerItem.setFocusableInTouchMode(true);
}else{
ImageView imageViewDrawerIcon = (ImageView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.imageViewDrawerIcon);
TextView textViewDrawerTitle = (TextView) recyclerViewDrawer.getChildAt(i).findViewById(R.id.textViewDrawerItemTitle);
imageViewDrawerIcon.setColorFilter(getResources().getColor(R.color.md_text));
if(Build.VERSION.SDK_INT > 15){
imageViewDrawerIcon.setImageAlpha(138);
}else{
imageViewDrawerIcon.setAlpha(138);
}
textViewDrawerTitle.setTextColor(getResources().getColor(R.color.md_text));
RelativeLayout relativeLayoutDrawerItem = (RelativeLayout) recyclerViewDrawer.getChildAt(i).findViewById(R.id.relativeLayoutDrawerItem);
relativeLayoutDrawerItem.setFocusableInTouchMode(false);
}
}
//TODO Fragments (closedrawers before setfragment)
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after some time
}
}, 250);
mDrawerLayout.closeDrawers();
}
});
In my case it,is work like a charm
View viewItem = recycleView.getLayoutManager().findViewByPosition(position);
View icon = viewItem.findViewById(R.id.view);
I solved finally with this (source):
recyclerViewDrawer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ImageView imageViewDrawerIcon = (ImageView) recyclerViewDrawer.getChildAt(0).findViewById(R.id.imageViewDrawerIcon);
TextView textViewDrawerTitle = (TextView) recyclerViewDrawer.getChildAt(0).findViewById(R.id.textViewDrawerItemTitle);
imageViewDrawerIcon.setColorFilter(color);
if (Build.VERSION.SDK_INT > 15) {
imageViewDrawerIcon.setImageAlpha(255);
} else {
imageViewDrawerIcon.setAlpha(255);
}
textViewDrawerTitle.setTextColor(color);
RelativeLayout relativeLayoutDrawerItem = (RelativeLayout) recyclerViewDrawer.getChildAt(0).findViewById(R.id.relativeLayoutDrawerItem);
relativeLayoutDrawerItem.setFocusableInTouchMode(true);
// unregister listener (this is important)
recyclerViewDrawer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
By the way, if someone have a better solution I would like to know it.
This worked for me.
recyclerView.post(new Runnable() {
#Override
public void run() {
View viewItem = recycleView.getLayoutManager().findViewByPosition(position);
View icon = viewItem.findViewById(R.id.view);
}
});
I would use findViewHolderForAdapterPosition() or findViewByPosition() instead to find the root view at that index. The way you ensure the data is loaded is up to you, however.
findViewByPosition is a method of LayoutManager, which works with all LayoutManagers.
So you can use recycleView.getLayoutManager() and findViewByPosition(pos).
Also recyclerView.findViewHolderForAdapterPosition(pos) works too.
For more information, look at this RecyclerView - Get view at particular position

Android calendar event use gridview listview

http://i.imgur.com/PyO4q.png?1
This image is using the gridview to make a calendar, but now I want to add a new event in "day". So I thought to use the listview inside the gridview-day, but the problem is the listview doesn't scroll. I think maybe the listview scroll collides with gridview. Please give me some idea to solve this problem.
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
TextView present;
TextView meeting;
TextView other;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView)v.findViewById(R.id.date);
present=(TextView)v.findViewById(R.id.ptextView1);
meeting=(TextView)v.findViewById(R.id.mtextView2);
other=(TextView)v.findViewById(R.id.otextView3);
// listitem=(ListView)v.findViewById(R.id.calendarlist);
// listitem.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.item_background_focused);
}
else {
v.setBackgroundResource(R.drawable.list_item_background);
}
}
dayView.setText(days[position]);
present.setVisibility(View.GONE);
meeting.setVisibility(View.GONE);
other.setVisibility(View.GONE);
for(int t=0;t<date1.size();t++){
if(returndouble(dayView.getText().toString()).equals(date1.get(t).get(3))){
if(date1.get(t).get(1).equals("Presented")){
meeting.setVisibility( View.VISIBLE);
}else if(date1.get(t).get(1).equals("Present")){
present.setVisibility( View.VISIBLE);
}else{
other.setVisibility( View.VISIBLE);
}
}
}
// create date string for comparison
String date = days[position];
if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}
// show icon if date is not empty and it exists in the items array
// ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
/* if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}*/
return v;
}
public void refreshDays()
{
// clear items
items.clear();
Calendardb date=new Calendardb(mContext);
date1= date.calendarselect(String.valueOf( month.get(Calendar.YEAR))+"/"+returndouble(String.valueOf((month.get(Calendar.MONTH)+1))));
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}

Categories

Resources