Recyclerview horizontal with a bottom line indicator - android

I have a horizontal recycleview which can scroll & snap center. Then I want a bottom line indicator to indicate selected item when click on it. It looks like this:
I had a look at this library but it doesn't fit my requirements.
Is there idea to implement this one?
Update: I need to keep the indicator is always visible and has a smooth scroll when moving to another position like above gift

You can try the following code:
DateTabIndicator.java
public class DateTabIndicator extends FrameLayout implements View.OnClickListener {
private List<Integer> days = new ArrayList<>();
private int selectedPageIndex = 0;
private int selectedDayIndex = 0;
private static final int[] DAY_TV_RES_ID = {R.id.day_mon, R.id.day_tue, R.id.day_wed, R.id.day_thu, R.id.day_fri, R.id.day_sat,
R.id.day_sun};
public DateTabIndicator(#NonNull Context context) {
super(context);
init();
}
public DateTabIndicator(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public DateTabIndicator(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private TextView monFixedIndicator;
private TextView tueFixedIndicator;
private TextView wedFixedIndicator;
private TextView thuFixedIndicator;
private TextView friFixedIndicator;
private TextView satFixedIndicator;
private TextView sunFixedIndicator;
private View lineIndicator;
private ViewPager daysPager;
private DaysPagerAdapter daysPagerAdapter;
private Handler mHandler = new Handler();
private void init() {
addView(LayoutInflater.from(getContext()).inflate(R.layout.date_tab_indicator, this, false));
monFixedIndicator = findViewById(R.id.mon_fixed_indicator);
tueFixedIndicator = findViewById(R.id.tue_fixed_indicator);
wedFixedIndicator = findViewById(R.id.wed_fixed_indicator);
thuFixedIndicator = findViewById(R.id.thu_fixed_indicator);
friFixedIndicator = findViewById(R.id.fri_fixed_indicator);
satFixedIndicator = findViewById(R.id.sat_fixed_indicator);
sunFixedIndicator = findViewById(R.id.sun_fixed_indicator);
lineIndicator = findViewById(R.id.line_indicator);
daysPager = findViewById(R.id.days_pager);
daysPagerAdapter = new DaysPagerAdapter();
daysPager.setAdapter(daysPagerAdapter);
daysPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
selectedPageIndex = position;
mHandler.removeCallbacks(selectDayRunnable);
mHandler.postDelayed(selectDayRunnable,500);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mHandler.postDelayed(selectDayRunnable,500);
}
class DaysPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return (int) Math.ceil(days.size() / 7f);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, final int position) {
final View view = LayoutInflater.from(getContext()).inflate(R.layout.days_pager_item, container, false);
TextView dayMonTv = view.findViewById(R.id.day_mon);
TextView dayTueTv = view.findViewById(R.id.day_tue);
TextView dayWedTv = view.findViewById(R.id.day_wed);
TextView dayThuTv = view.findViewById(R.id.day_thu);
TextView dayFriTv = view.findViewById(R.id.day_fri);
TextView daySatTv = view.findViewById(R.id.day_sat);
TextView daySunTv = view.findViewById(R.id.day_sun);
//Setting Day Text
int index = position * 7;
dayMonTv.setText(days.size() > index ? String.valueOf(days.get(index)) : "");
dayTueTv.setText(days.size() > (++index) ? String.valueOf(days.get(index)) : "");
dayWedTv.setText(days.size() > (++index) ? String.valueOf(days.get(index)) : "");
dayThuTv.setText(days.size() > (++index) ? String.valueOf(days.get(index)) : "");
dayFriTv.setText(days.size() > (++index) ? String.valueOf(days.get(index)) : "");
daySatTv.setText(days.size() > (++index) ? String.valueOf(days.get(index)) : "");
daySunTv.setText(days.size() > (++index) ? String.valueOf(days.get(index)) : "");
//Setting Day VISIBILITY
index = position * 7;
dayMonTv.setVisibility(days.size() > index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
dayTueTv.setVisibility(days.size() > ++index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
dayWedTv.setVisibility(days.size() > ++index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
dayThuTv.setVisibility(days.size() > ++index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
dayFriTv.setVisibility(days.size() > ++index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
daySatTv.setVisibility(days.size() > ++index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
daySunTv.setVisibility(days.size() > ++index && days.get(index) != 0 ? VISIBLE : INVISIBLE);
//Setting Selection
dayMonTv.setSelected(false);
dayTueTv.setSelected(false);
dayWedTv.setSelected(false);
dayThuTv.setSelected(false);
dayFriTv.setSelected(false);
daySatTv.setSelected(false);
daySunTv.setSelected(false);
//Setting Click Listener
dayMonTv.setOnClickListener(DateTabIndicator.this);
dayTueTv.setOnClickListener(DateTabIndicator.this);
dayWedTv.setOnClickListener(DateTabIndicator.this);
dayThuTv.setOnClickListener(DateTabIndicator.this);
dayFriTv.setOnClickListener(DateTabIndicator.this);
daySatTv.setOnClickListener(DateTabIndicator.this);
daySunTv.setOnClickListener(DateTabIndicator.this);
view.setTag(position);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
public List<Integer> getDays() {
return days;
}
public void setDays(List<Integer> days) {
this.days = days;
daysPagerAdapter.notifyDataSetChanged();
}
private View prevDayTv = null;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.day_mon:
selectDay(v, 0);
break;
case R.id.day_tue:
selectDay(v, 1);
break;
case R.id.day_wed:
selectDay(v, 2);
break;
case R.id.day_thu:
selectDay(v, 3);
break;
case R.id.day_fri:
selectDay(v, 4);
break;
case R.id.day_sat:
selectDay(v, 5);
break;
case R.id.day_sun:
selectDay(v, 6);
break;
}
}
/**
* #param dayIndex 0-6
*/
private void selectDay(View v, int dayIndex) {
selectedDayIndex = dayIndex;
int dayListIndex = selectedPageIndex * 7 + dayIndex;
if (prevDayTv != null) prevDayTv.setSelected(false);
v.setSelected(true);
prevDayTv = v;
int[] location = new int[2];
v.getLocationOnScreen(location);
int center_point = location[0]%getWidth() + v.getWidth() / 2;
lineIndicator.animate().x(center_point - lineIndicator.getWidth() / 2);
if (days.size() > dayListIndex && days.get(dayListIndex)!=0) {
//listener
} else {
for (int i = 0; i < 7; i++) {
dayListIndex = selectedPageIndex * 7 + i;
if (days.get(dayListIndex)==1 || days.size()-1 == dayListIndex) {
setSelectedDay(i);
break;
}
}
}
}
/**
* #param dayIndex 0-6
*/
public void setSelectedDay(int dayIndex) {
if (dayIndex >= 0 && dayIndex < 7) {
selectedDayIndex = dayIndex;
View view = daysPager.findViewWithTag(selectedPageIndex);
selectDay(view.findViewById(DAY_TV_RES_ID[dayIndex]),dayIndex);
}
}
private Runnable selectDayRunnable = new Runnable() {
#Override
public void run() {
setSelectedDay(selectedDayIndex);
}
};
}
date_tab_indicator.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/mon_to_sun_lay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/mon_fixed_indicator"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="M" />
<TextView
android:id="#+id/tue_fixed_indicator"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="T" />
<TextView
android:id="#+id/wed_fixed_indicator"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="W" />
<TextView
android:id="#+id/thu_fixed_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="T" />
<TextView
android:id="#+id/fri_fixed_indicator"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="F" />
<TextView
android:id="#+id/sat_fixed_indicator"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="S" />
<TextView
android:id="#+id/sun_fixed_indicator"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_weight="1"
android:gravity="center"
android:text="S" />
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="#+id/days_pager"
android:layout_width="match_parent"
android:layout_height="50dp" />
<View
android:id="#+id/line_indicator"
android:layout_width="15dp"
android:layout_height="3dp"
android:padding="5dp"
android:background="#000000"
/>
</LinearLayout>
days_pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_mon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_tue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_wed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_thu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_fri"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_sat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
<FrameLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/day_sun"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/day_circle_bg"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#color/day_color_selector" />
</FrameLayout>
</LinearLayout>
days_color_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#000000"></item>
<item android:state_selected="false" android:color="#bdbebd"></item>
</selector>
days_circle_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="40dp"
android:height="40dp" />
<stroke android:width="1dp"
android:color="#bdbebd"
/>
</shape>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private DateTabIndicator dateTabIndicator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateTabIndicator = findViewById(R.id.date_tab_indicator);
dateTabIndicator.setDays(Arrays.asList(new Integer[]{0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31}));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<com.karacken.datetabindicator.DateTabIndicator
android:id="#+id/date_tab_indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
Output:

How to build a Horizontal ListView with RecyclerView?
check the answer of "Suragch" and plus addition to that answer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
//use your entire xml code here plus place a image view as
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below = "id of the date circle"
android:background = "add a line of length according to your requirement in drawables and assign here"
android:visibility="set to invisible"/>
/RelativeLayout>
then inside of onClick() method inside ViewHolder class set the visibilty of the ImageView to visible by Calling imageView.setVisibility(View.VISIBLE) and callnotifyDataSetChanged()
Hope it is helping...

You can change indicator position by trigger the RecycleView item selected change. For item selected change, you can use a variable to keep the selected position in adapter. When user fling the RecycleView, use have calculate selected position based on position of indicator.

Related

Fragment is too slow when change on bottomnavigatioview?

My Fragment is taking so much time in update layout It is because of a lot of code in fragment how to resolve this please help me
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/lyttabs"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:gravity="center"
android:layout_marginTop="20dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.bugfree.caviar.fonts.BabesNeueProBold
android:textStyle="bold"
android:layout_weight="1"
android:textColor="#color/black_text"
android:textSize="30dp"
android:layout_width="0dp"
android:text="My Events That I am..."
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/btn_plus"
android:src="#drawable/plus"
android:layout_width="20dp"
android:layout_height="20dp" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabLayout
app:tabIndicatorColor="#color/button_red_back"
android:id="#+id/tabs"
android:layout_marginTop="15dp"
app:tabBackground="#drawable/tab_indicator_color"
app:tabTextAppearance="#style/MyCustomTextAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager.widget.ViewPager
android:layout_marginTop="30dp"
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</LinearLayout>
<LinearLayout android:id="#+id/lytCreateEvent"
android:visibility="gone"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.CreateEvent">
<ImageView
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp"
android:layout_marginTop="30dp"
android:id="#+id/imgBack"
android:src="#drawable/back_black"
android:layout_width="20dp"
android:layout_height="20dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_marginEnd="15dp"
android:layout_marginStart="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<com.bugfree.caviar.fonts.BabesNeueProBold
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create event"
android:textColor="#color/black"
android:textSize="30dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="vertical">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event title" />
<EditText
android:singleLine="true"
android:paddingStart="15dp"
android:layout_marginTop="10dp"
android:textColorHint="#color/black"
android:background="#drawable/edit_back"
android:id="#+id/edtEventTitle"
android:textSize="18dp"
android:layout_gravity="center"
android:hint="Beach Yoga!"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event type" />
</LinearLayout>
<RelativeLayout
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:gravity="center"
android:background="#drawable/edit_back"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_centerVertical="true"
android:paddingStart="15dp"
android:layout_width="wrap_content"
android:textColor="#color/black"
android:layout_height="wrap_content"
android:text="Business"
android:textSize="18dp" />
<ImageView
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginEnd="15dp"
android:layout_width="12dp"
android:layout_height="12dp"
android:layout_alignParentEnd="true"
android:src="#drawable/down_arrow" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event description" />
<com.bugfree.caviar.fonts.BabesNeueProBoldRegular
android:layout_marginEnd="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:text="94/300" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/custombutton_border_edittext"
android:orientation="vertical">
<EditText
android:textSize="18dp"
android:id="#+id/edtDescription"
android:textColorHint="#color/black_text_new"
android:padding="10dp"
android:layout_gravity="start"
android:gravity="start"
android:hint="Beach yoga with Alissia is a lifestyle focused on health,
wellness, and self-care through the practice of"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#android:color/transparent" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<ImageView
android:layout_marginEnd="10dp"
android:layout_centerVertical="true"
android:tint="#color/black"
android:layout_alignParentEnd="true"
android:src="#drawable/down_arrowsmall"
android:layout_width="10dp"
android:layout_height="10dp" />
</RelativeLayout>
<EditText
android:paddingLeft="10dp"
android:layout_gravity="start"
android:gravity="start"
android:id="#+id/edtSplReq"
android:layout_width="match_parent"
android:layout_marginTop="15dp"
android:layout_height="100dp"
android:singleLine="true"
android:padding="10dp"
android:background="#drawable/lay_without_border"
android:hint="Add a special request[optional]"
android:textColorHint="#848484"
android:textSize="18dp" />
<Button
android:outlineProvider="bounds"
android:stateListAnimator="#null"
style="?android:attr/borderlessButtonStyle"
android:layout_marginBottom="35dp"
android:id="#+id/btnSubmit"
android:layout_marginTop="30dp"
android:textSize="18dp"
android:textAllCaps="false"
android:text="Submit"
android:textColor="#color/space_white"
android:background="#drawable/custombutton"
android:layout_width="match_parent"
android:layout_height="35dp" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="#+id/lytTab"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabLayout
app:tabBackground="#drawable/tab_indicator_color"
app:tabIndicatorColor="#color/button_red_back"
android:id="#+id/tabsLOc"
android:layout_marginTop="10dp"
app:tabTextAppearance="#style/MyCustomTextAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPagerLoc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and here is my fragment
public class EventFragment extends Fragment {
private View view;
ViewPagerAdapter viewPagerAdapter;
LocationPagerAdapter locationPagerAdapter;
private String current = "";
private String ddmmyyyy = "MMDDYYYY";
private Calendar cal = Calendar.getInstance();
FragmentEventBinding binding;
private OnFragmentInteractionListener mListener;
public EventFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(
inflater, R.layout.fragment_event, container, false);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Bebas Neue Pro Regular.otf");
binding.lytTopImg.setOnClickListener(v -> {
binding.lytLocDetails.setVisibility(View.VISIBLE);
binding.lytPartLocNew.setVisibility(View.GONE);
});
binding.imgTopEvent.setImageBitmap(SetBrightness(BitmapFactory.decodeResource(getResources(), R.drawable.dummy),-70));
binding.imgBackLocDetail.setOnClickListener(v -> {
binding.lytLocDetails.setVisibility(View.GONE);
binding.lytPartLocNew.setVisibility(View.VISIBLE);
/* Intent intent = new Intent(PartnerLocationActivity.this, LoactionDetails.class);
startActivity(intent);*/
});
binding.btnPlus.setOnClickListener(v -> {
binding.lyttabs.setVisibility(View.GONE);
binding.lytCreateEvent.setVisibility(View.VISIBLE);
});
binding.imgBack.setOnClickListener(v -> {
mListener.changeFragment(2);
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
});
binding.buttonCreateEvent.setOnClickListener(v -> {
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
});
binding.imgBackPartnerLoc.setOnClickListener(v -> {
binding.lytPartLocNew.setVisibility(View.GONE);
binding.lytCreateEvent.setVisibility(View.VISIBLE);
/* Intent intent = new Intent(getActivity(), CreateEvent.class);
startActivity(intent);*/
});
binding.lytTopPartLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
binding.lytLocDetails.setVisibility(View.VISIBLE);
binding.lytPartLocNew.setVisibility(View.GONE);
}
});
binding.buttonCreateEvent.setTypeface(font);
binding.edtEventTitle.setTypeface(font);
binding.edtDescription.setTypeface(font);
binding.edtNameLoc.setTypeface(font);
binding.edtAddressLoc.setTypeface(font);
binding.rdbOne.setTypeface(font);
binding.rdbGroup.setTypeface(font);
binding.buttonPartnerloc.setOnClickListener(v -> {
binding.lytPartLocNew.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
/* Intent intent = new Intent(CreateEvent.this, PartnerLocationActivity.class);
startActivity(intent);*/
});
binding.buttonCreateEvent.setOnClickListener(v -> {
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytCreateEvent.setVisibility(View.GONE);
});
binding.edtDob.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
String clean = s.toString().replaceAll("[^\\d.]|\\.", "");
String cleanC = current.replaceAll("[^\\d.]|\\.", "");
int cl = clean.length();
int sel = cl;
for (int i = 2; i <= cl && i < 6; i += 2) {
sel++;
}
if (clean.equals(cleanC)) sel--;
if (clean.length() < 8) {
clean = clean + ddmmyyyy.substring(clean.length());
} else {
int day = Integer.parseInt(clean.substring(0, 2));
int mon = Integer.parseInt(clean.substring(2, 4));
int year = Integer.parseInt(clean.substring(4, 8));
mon = mon < 1 ? 1 : mon > 12 ? 12 : mon;
cal.set(Calendar.MONTH, mon - 1);
year = (year < 1900) ? 1900 : (year > 2100) ? 2100 : year;
cal.set(Calendar.YEAR, year);
day = (day > cal.getActualMaximum(Calendar.DATE)) ? cal.getActualMaximum(Calendar.DATE) : day;
clean = String.format("%02d%02d%02d", day, mon, year);
}
clean = String.format("%s/%s/%s", clean.substring(0, 2),
clean.substring(2, 4),
clean.substring(4, 8));
sel = sel < 0 ? 0 : sel;
current = clean;
binding.edtDob.setText(current);
binding.edtDob.setSelection(sel < current.length() ? sel : current.length());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
try {
}catch (Exception ignored){
}
}
}).start();
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
binding.viewPager.setAdapter(viewPagerAdapter);
binding.tabs.setupWithViewPager( binding.viewPager);
/*binding.imgBack.setOnClickListener(v -> {
binding.lytLocDetails.setVisibility(View.GONE);
binding.lytPartLocNew.setVisibility(View.VISIBLE);
});*/
locationPagerAdapter = new LocationPagerAdapter(getFragmentManager());
binding.viewPagerLoc.setAdapter(locationPagerAdapter);
binding.tabsLOc.setupWithViewPager(binding.viewPagerLoc);
binding.edtSplReq.setTypeface(font);
binding.edtEmail.setTypeface(font);
binding.edtPhone.setTypeface(font);
binding.edtLastName.setTypeface(font);
binding.edtFirstname.setTypeface(font);
binding.btnSubmit.setTypeface(font);
binding.btnFindTable.setTypeface(font);
binding.btnFindTable.setOnClickListener(v -> {
binding.lytBtnFind.setVisibility(View.GONE);
binding.lytTab.setVisibility(View.GONE);
binding.lytBookTable.setVisibility(View.VISIBLE);
});
binding.btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
binding.lyttabs.setVisibility(View.VISIBLE);
binding.lytLocDetails.setVisibility(View.GONE);
binding.lytPartLocNew.setVisibility(View.GONE);
binding.lytCreateEvent.setVisibility(View.GONE);
binding.lytBookTable.setVisibility(View.GONE);
binding.lytBtnFind.setVisibility(View.VISIBLE);
binding.lytTab.setVisibility(View.VISIBLE);
binding.viewPager.setCurrentItem(1);
binding.tabs.getSelectedTabPosition();
}
});
return view = binding.getRoot();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public Bitmap SetBrightness(Bitmap src, int value) {
// original image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
// increase/decrease each channel
R += value;
if(R > 255) { R = 255; }
else if(R < 0) { R = 0; }
G += value;
if(G > 255) { G = 255; }
else if(G < 0) { G = 0; }
B += value;
if(B > 255) { B = 255; }
else if(B < 0) { B = 0; }
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
// return final image
return bmOut;
}
}
There are two parts to this answer.
As per https://developer.android.com/topic/performance/rendering/optimizing-view-hierarchies
Android Layouts allow you to nest UI objects in the view hierarchy. This nesting can also impose a layout cost.
Your layout has multiple levels of nesting, this can have a large cost to layout.
Simplifying you layout with a more flexible layout like a ConstraintLayout Might reduce the layout cost.
Sometimes you are just trying to do too much when creating a view, do some of the work in a background thread and update the view when done (optionally putting up a busy type of progress bar while doing it)
Some idea's based on your code shown.
Instead of scanning every pixel of an image with the SetBrightness method which could take some time depending on the size of the image.
Add the image to the layout without the Brightness adjusted, start background task adjust image Brightness and when done replace the original un-adjusted image with the adjusted image.
This could probably be done without a busy progress bar.
Delay the creation of the offscreen viewpager pages until they are really needed.
Instead of each Fragment in the viewpager creating it's view in onCreateView when the Viewpager is created, create a placeholder view in the Fragment's onCreateView and update it in the Fragment's onResume which is only called when the Fragment is shown on screen (note need a recent'ish version of Viewpager for this behaviour)

How to scroll to chip when clicked in horizontal scroll view?

I have a HorizontalScrollView with a ChipGroup and some Chips. When I check a Chip which is cut out of the screen I want the ScrollView to snap to and show it fully.
This is how it looks like when I select it.
My layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorWhite"
android:theme="#style/Theme.MaterialComponents">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="165dp" />
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="120dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<HorizontalScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.chip.ChipGroup
android:id="#+id/chip_group"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:chipSpacingHorizontal="10dp"
app:singleLine="true"
app:singleSelection="true"
app:selectionRequired="true">
<com.google.android.material.chip.Chip
android:id="#+id/chip_all"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_marginLeft="15dp"
android:backgroundTint="#color/indicator_chips"
android:checkable="true"
app:chipCornerRadius="10dp"
android:text="ALL"
android:textColor="#color/indicator_text"
app:checkedIconEnabled="false"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_watching"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="WATCHING"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_completed"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="COMPLETED"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_onhold"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="ON HOLD"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_dropped"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:checkable="true"
android:text="DROPPED"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
<com.google.android.material.chip.Chip
android:id="#+id/chip_plantowatch"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_marginRight="15dp"
android:checkable="true"
android:text="PLAN TO WATCH"
android:textColor="#color/indicator_text"
app:chipCornerRadius="10dp"
app:checkedIconEnabled="false"
android:backgroundTint="#color/indicator_chips"
app:chipStrokeColor="#color/indicator_stroke"
app:chipStrokeWidth="1dp" />
</com.google.android.material.chip.ChipGroup>
</HorizontalScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
And my class file:
public class LibraryFragment extends Fragment {
private HorizontalScrollView scrollView;
Chip chip_dropped;
ChipGroup chipGroup;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_library_anime, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
scrollView = view.findViewById(R.id.scroll_view);
chipGroup = view.findViewById(R.id.chip_group);
chipGroup.setOnCheckedChangeListener(checkedListener);
}
ChipGroup.OnCheckedChangeListener checkedListener = new ChipGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
switch (group.getCheckedChipId()) {
case R.id.chip_all:
fragmentTransaction.replace(R.id.fragment_container, new ListALL()).commit();
break;
case R.id.chip_watching:
fragmentTransaction.replace(R.id.fragment_container, new ListWATCHING()).commit();
break;
case R.id.chip_completed:
fragmentTransaction.replace(R.id.fragment_container, new ListCOMPLETED()).commit();
break;
case R.id.chip_onhold:
fragmentTransaction.replace(R.id.fragment_container, new ListONHOLD()).commit();
break;
case R.id.chip_dropped:
fragmentTransaction.replace(R.id.fragment_container, new ListDROPPED()).commit();
break;
case R.id.chip_plantowatch:
fragmentTransaction.replace(R.id.fragment_container, new ListPLANTOWATCH()).commit();
break;
}
}
};
}
So to repeat, I'm trying to make my ScrollView scroll to a Chip when it is clicked, like the play store with its. I tried .scroolTo and .smoothScrollTo but non of it work.
I made a sample project for You. I think You can easily convert it to Your app.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
HorizontalScrollView scroll;
int widthScreen;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
widthScreen = displayMetrics.widthPixels;
scroll = findViewById(R.id.scroll);
LinearLayout linearLayout = findViewById(R.id.linLay);
for (int index = 0; index <= linearLayout.getChildCount() - 1; index++)
{
linearLayout.getChildAt(index).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Rect r = new Rect();
v.getGlobalVisibleRect(r);
if (r.right == widthScreen)
{
Rect rr = new Rect();
v.getDrawingRect(rr);
scroll.smoothScrollBy(rr.right - (widthScreen - r.left), 0);
}
else if (r.left == 0)
{
Rect rr = new Rect();
v.getDrawingRect(rr);
scroll.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
}
}
});
}
}
}
MainActivity.XML (just buttons in ScrollView)
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linLay"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9" />
</LinearLayout>
</HorizontalScrollView>
When You click on the button which is not fully on-screen ScrollView will be scrolled to a proper position to show full button.
Using the code that #iknow posted, I change it to work exactly like the play store with its Chips
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
chipGroup = view.findViewById(R.id.chip_group);
final Chip chip_all = view.findViewById(R.id.chip_all);
final Chip chip_watching = view.findViewById(R.id.chip_watching);
final Chip chip_completed = view.findViewById(R.id.chip_completed);
final Chip chip_onhold = view.findViewById(R.id.chip_onhold);
final Chip chip_dropped = view.findViewById(R.id.chip_dropped);
final Chip chip_plantowatch = view.findViewById(R.id.chip_plantowatch);
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
widthScreen = displayMetrics.widthPixels;
scrollView = view.findViewById(R.id.scroll_view);
chipGroup = view.findViewById(R.id.chip_group_anime);
for (int index = 0; index <= chipGroup.getChildCount() - 1; index++) {
chipGroup.getChildAt(index).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Rect r = new Rect();
view.getGlobalVisibleRect(r);
if(chip_all.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
}
if(chip_watching.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
}
if(chip_completed.isChecked()) {
scrollView.smoothScrollTo(chip_completed.getLeft() - (widthScreen / 2) + (chip_completed.getWidth() / 2), 0);
}
if(chip_onhold.isChecked()) {
scrollView.smoothScrollTo(chip_onhold.getLeft() - (widthScreen / 2) + (chip_onhold.getWidth() / 2), 0);
}
if(chip_dropped.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(r.right, 0);
}
if(chip_plantowatch.isChecked()) {
Rect rr = new Rect();
view.getDrawingRect(rr);
scrollView.smoothScrollBy(r.right, 0);
}
}
});
}
}
The end product looks like the gif above and again thank you to #iknow who provided the code!

How to make Horizontal line attach textview in recyclerview?

Am having a doubt regarding how to make the horizontal view to touch the textview while populating in recyclerview , Now let me explain briefly i having a horizontal recyclerview in that adapter view holder i have horizontal view at the end of the textview which is center vertical to that textview, so when items are added each view must touch the textview like vertical dotted timeline but the view is not touching the textview as shown in the below image.
Now let me post what i have tried so far
This is the layout that holding recyclerview:
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" >
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview"/>
</RelativeLayout>
Here am using that recyclerview in activity:
Recyclerview recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setHasFixedSize(true);
TrackingAdapter mAdapter = new TrackingAdapter(this.taskLogModelList,mTaskModel.getTaskID(),fm,String.valueOf(mLastLocation.getLatitude()),String.valueOf(mLastLocation.getLongitude()));
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
Here is the adapter am using :
public class TrackingAdapter extends RecyclerView.Adapter<TrackingAdapter.ViewHolder> {
private List<TaskLogModel> taskStatusFlowModels;
private D2DKnocks appclass;
private String Lat,Long;
private FragmentManager fragmentManager;
private String TaskID;
DateFormat date,msimpleDateformat;
public TrackingAdapter(List<TaskLogModel> taskStatusFlowModels,String TaskID,FragmentManager context,String Lat,String Long) {
this.taskStatusFlowModels = taskStatusFlowModels;
this.fragmentManager=context;
date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
msimpleDateformat = new SimpleDateFormat("hh.mm a");
this.Lat=Lat;
this.TaskID=TaskID;
this.Long=Long;
appclass=((D2DKnocks)D2DKnocks.getContext());
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private AvertaTextview txt_time;
private Rubik txt_delivered;
// private AvertaButton btn_start;
private RelativeLayout layout;
private View view_right;
public ViewHolder(View itemView) {
super(itemView);
txt_time = itemView.findViewById(R.id.txt_time);
// btn_start=itemView.findViewById(R.id.start);
layout=itemView.findViewById(R.id.layout);
txt_delivered = itemView.findViewById(R.id.txt_delivered);
view_right = (View) itemView.findViewById(R.id.right_view_line);
layout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
TaskLogModel taskLogModel=taskStatusFlowModels.get(getAdapterPosition());
if(taskLogModel.getTaskStatusID()==0){
TaskStatusDialog taskStatusDialog=new TaskStatusDialog();
Bundle bundle=new Bundle();
bundle.putInt("Size",taskStatusFlowModels.size());
bundle.putString("Lat",Lat);
bundle.putString("Long",Long);
bundle.putString("TaskID",TaskID);
taskStatusDialog.setArguments(bundle);
taskStatusDialog.show(fragmentManager,"show");
}
}
}
#Override
public TrackingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_view_assignment_status, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(TrackingAdapter.ViewHolder holder, int position) {
if (taskStatusFlowModels.get(position).getTaskStatusID() > 0) {
StatusModel statusFlowModel = getStatusName(taskStatusFlowModels.get(position).getTaskStatusID());
holder.txt_delivered.setText(statusFlowModel.getStatus());
holder.txt_delivered.setBackgroundResource(R.drawable.btn_arrived_bg);
try {
Date uppdateDate=date.parse(taskStatusFlowModels.get(position).getUpdateDateTime());
String updatedDate=msimpleDateformat.format(uppdateDate);
String[] each = updatedDate.split(" ");
String str = each[1].replace("AM", "am").replace("PM","pm");
// SpannableString ss1= new SpannableString(each[0]);
// SpannableString ss2=new SpannableString(each[1]);
// ss1.setSpan(new AbsoluteSizeSpan(20), 0, each[0].length(), SPAN_INCLUSIVE_INCLUSIVE);
// ss2.setSpan(new AbsoluteSizeSpan(15), 0, each[1].length(), SPAN_INCLUSIVE_INCLUSIVE);
// CharSequence finalText = TextUtils.concat(ss1, " ", ss2);
holder.txt_time.setText(each[0]+" "+str);
} catch (ParseException e) {
e.printStackTrace();
}
GradientDrawable gradientDrawable = (GradientDrawable) holder.txt_delivered.getBackground();
gradientDrawable.setColor(Color.parseColor(statusFlowModel.getStatusColor()));
} else {
holder.txt_delivered.setText("Choose");
holder.txt_delivered.setBackgroundResource(R.drawable.btn_choose_bg);
holder.txt_delivered.setTextColor(Color.parseColor("#b1b1b1"));
}
if(taskStatusFlowModels.size()-1==position){
holder.view_right.setVisibility(View.GONE);
}
else {
holder.view_right.setVisibility(View.VISIBLE);
}
}
public StatusModel getStatusName(Integer statusID){
for (int i=0;i<appclass.getStatusModelist().size();i++){
if (appclass.getStatusModelist().get(i).getStatusID().equals(statusID)){
return appclass.getStatusModelist().get(i);
}
}
return null;
}
#Override
public int getItemCount() {
return taskStatusFlowModels.size();
}
}
And below is the view holder layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/layout">
<com.trident.Hawkersky.service.CustomFonts.AvertaTextview
android:id="#+id/txt_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:drawableLeft="#drawable/ic_checked"
android:drawablePadding="10dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="10.00 am"
android:textColor="#444444"
android:textSize="12sp"
/>
<View
android:id="#+id/vertical_line"
android:layout_width="30dp"
android:layout_height="20dp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/txt_time"
android:background="#drawable/vertical_dotted_line"
android:layerType="software"
android:visibility="visible" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_below="#+id/vertical_line"
android:layout_height="wrap_content">
<com.trident.Hawkersky.service.CustomFonts.Rubik
android:id="#+id/txt_delivered"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="#dimen/thirty"
android:layout_marginBottom="5dp"
android:singleLine="true"
android:padding="#dimen/seven"
android:background="#drawable/btn_delivered_bg"
android:gravity="center"
android:text="Delivered"
android:textAllCaps="true"
android:textColor="#FFF"
android:textSize="13sp"
android:textStyle="bold" />
<View
android:id="#+id/right_view_line" <--- this is the view
android:layout_width="#dimen/hundred"
android:layout_height="5dp"
android:layout_alignBottom="#+id/txt_delivered"
android:layout_gravity="center_vertical"
android:layout_marginBottom="12dp"
android:layout_toEndOf="#+id/txt_delivered"
android:layout_toRightOf="#+id/txt_delivered"
android:background="#drawable/dotted"
android:layerType="software"
android:visibility="visible" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
Now what i need is i need that view to attach to the textview , but am getting like image above how to solve it.
Please try this and let know if you need further modifications.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical">
<com.trident.Hawkersky.service.CustomFonts.AvertaTextview
android:id="#+id/txt_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:drawableLeft="#drawable/ic_checked"
android:drawablePadding="10dp"
android:gravity="center"
android:text="10.00 am"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="#+id/txt_delivered"
app:layout_constraintRight_toRightOf="#+id/txt_delivered"
android:textColor="#444444"
android:textSize="12sp"
/>
<View
android:id="#+id/vertical_line"
android:layout_width="30dp"
android:layout_height="20dp"
app:layout_constraintLeft_toLeftOf="#+id/txt_delivered"
app:layout_constraintRight_toRightOf="#+id/txt_delivered"
android:layout_below="#+id/txt_time"
android:layout_centerHorizontal="true"
app:layout_constraintTop_toBottomOf="#+id/txt_time"
android:background="#color/colorPrimaryDark"
android:layerType="software"
android:visibility="visible"/>
<com.trident.Hawkersky.service.CustomFonts.Rubik
android:id="#+id/txt_delivered"
android:layout_width="wrap_content"
android:layout_height="#dimen/thirty"
android:layout_marginBottom="5dp"
android:background="#drawable/btn_delivered_bg"
android:gravity="center"
app:layout_constraintTop_toBottomOf="#+id/vertical_line"
android:padding="#dimen/seven"
android:singleLine="true"
android:text="Delivered"
android:textAllCaps="true"
android:textColor="#FFF"
android:textSize="13sp"
android:textStyle="bold"/>
<View
android:id="#+id/right_view_line"
android:layout_width="100dp"
android:layout_height="5dp"
app:layout_constraintTop_toTopOf="#+id/txt_delivered"
app:layout_constraintBottom_toBottomOf="#+id/txt_delivered"
app:layout_constraintLeft_toRightOf="#+id/txt_delivered"
android:background="#drawable/dotted"
android:layerType="software"
android:visibility="visible"/>
</android.support.constraint.ConstraintLayout>
Sorry, I had to use ConstraintLayout. If you haven't been using it before, please add this implementation 'com.android.support.constraint:constraint-layout:1.0.2'1 to your module level build.gradle.

Two views with different heights in a viewflipper on a gridview tile

I have a GridView which has a ViewFlipper in each tile. Each view in the ViewFlipper has a different size, but when the tile is flipped, both views are forced to the same size as the GridView column. What i've tried:
Googled
Set android:measureAllChildren to false on ViewFlipper(only works with ListView)
Left android:columnWidth unspecified
Made ViewFlipper root tag in grid tile layout file
grid_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp" android:layout_height="150dp">
<ViewFlipper
android:layout_width="match_parent"
android:layout_height="match_parent"
android:measureAllChildren="false"
android:id="#+id/view_flipper_3"
>
<RelativeLayout
android:layout_width="180dp"
android:layout_height="150dp"
android:id="#+id/front2"
android:background="#088980"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/commitmentNumber"
android:textSize="25dp"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="220dp"
android:layout_height="190dp"
android:background="#000000"
android:id="#+id/back_2"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:id="#+id/commitmentPartOne"
android:paddingBottom="5dp"
android:textSize="25sp"
android:text="Part One"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/commitmentPartTwo"
android:textSize="25sp"
android:text="Part Two"
android:paddingBottom="5dp"
android:layout_below="#+id/commitmentPartOne"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/commitmentPartThree"
android:textSize="25sp"
android:text="Part Three"
android:layout_below="#+id/commitmentPartTwo"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</ViewFlipper>
</RelativeLayout>
fragment_with_gridview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sixCommitmentsGridView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:numColumns="2"
android:gravity="center"
android:columnWidth="179dp"
android:stretchMode="columnWidth"
/>
</RelativeLayout>
GridViewAdapter.java:
public class SixCommitmentsGridAdapter extends BaseAdapter {
Context context;
String[] numbers;
public SixCommitmentsGridAdapter(Context context, String[] numbers) {
this.context = context;
this.numbers = numbers;
}
#Override
public int getCount() {
return numbers.length;
}
#Override
public Object getItem(int position) {
return numbers[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
final ViewFlipper flipper;
TextView commitmentNumber;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.six_commitments_grid_item, parent, false);
}else{
view = convertView;
}
flipper = (ViewFlipper) view.findViewById(R.id.view_flipper_3);
commitmentNumber = (TextView) view.findViewById(R.id.commitmentNumber);
commitmentNumber.setText(numbers[position]);
flipper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position % 2 == 0 || position == 0){
AnimationFactory.flipTransition(flipper, AnimationFactory.FlipDirection.RIGHT_LEFT, 200);
}else {
AnimationFactory.flipTransition(flipper, AnimationFactory.FlipDirection.LEFT_RIGHT, 200);
}
}
});
return view;
}
}
Managed to achieve the same grid-style layout with my intented ViewFlipper effect using a StaggeredGridLayoutManager and a RecyclerView.
In Main RelativeLayout contain ViewFlipper, you set height and width!
set them "wrap_content"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
maybe worked.
good luck.
Update
Use this library:
https://github.com/etsy/AndroidStaggeredGrid

Issue inputting data in elements inside dynamic list

In the Android app I'm developing I'm loading a list of several items for the user to input some data; there's a checkbox and an EditText for each item, and the user can check the checkbox and type some notes regarding the item. This list is loaded dynamically from a local database, which in turn is populated from a remote database at a previous point. Now, the problem I'm having is that, whenever I focus on an EditText, after I lose focus on the element, the list seems to load again (elements which where unchecked/blank originally and had been checked/had text typed in them become unchecked/blank again, and those which were checked/had text initially go back to the original state). This only happens when I lose focus on the EditText; I can check and uncheck the checkboxes and they stay how I leave them (until I get and lose focus on an EditText). How can I avoid this so my elements retain the data?
I've tested the app in deviced with Android versions 3.2 and 4.2
Any help would be appreciated.
Here's the activity that loads the list:
public class PostventaPreentregaDetalleActivity extends Activity implements OnItemClickListener, OnItemSelectedListener {
private ArrayList<EncuestaPostventa> listaChequeoEncuesta;
private ArrayList<ConsumoBien> listaConsumoBien;
private ListView lvChequeoEncuesta;
private ListView lvConsumoBien;
private EncuestaPostventaAdapter adapter;
private ConsumoBienAdapter adapterConsumoBien;
public static DBProvider oDB;
#Override
public void onBackPressed() {
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.postventa_preentrega_detalle_activity_actions, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
getActionBar().setDisplayHomeAsUpEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postventa_preentrega_detalle);
listaChequeoEncuesta = new ArrayList<EncuestaPostventa>();
listaConsumoBien = new ArrayList<ConsumoBien>();
inicializarPestanas();
cargarDetalleNegocio();
listarChequeoEncuesta();
listarConsumoBien();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onItemClick(AdapterView<?> adapter, View view, int position,
long ID) {
}
public void cargarDetalleNegocio(){
Intent intent = getIntent();
TextView tvProyecto;
TextView tvCliente;
TextView tvRut;
TextView tvDireccion;
tvProyecto = (TextView) findViewById(R.id.tvProyecto);
tvRut = (TextView) findViewById(R.id.tvRut);
tvCliente = (TextView) findViewById(R.id.tvCliente);
tvDireccion = (TextView) findViewById(R.id.tvDireccion);
tvProyecto.setText(intent.getStringExtra("proyecto").trim());
tvRut.setText(intent.getStringExtra("rut").trim());
tvCliente.setText(intent.getStringExtra("cliente").trim());
tvDireccion.setText(intent.getStringExtra("direccion").trim());
}
public void inicializarPestanas(){
TabHost tabs = (TabHost)findViewById(android.R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec("tabChequeo");
spec.setContent(R.id.tabChequeo);
spec.setIndicator("Chequeo");
tabs.addTab(spec);
spec = tabs.newTabSpec("tabServicios");
spec.setContent(R.id.tabServicios);
spec.setIndicator("Servicios consumidos");
tabs.addTab(spec);
spec = tabs.newTabSpec("tabObservaciones");
spec.setContent(R.id.tabObservaciones);
spec.setIndicator("Observaciones");
tabs.addTab(spec);
tabs.setCurrentTab(0);
}
public void listarChequeoEncuesta(){
try{
oDB = new DBProvider(this);
Intent intent = getIntent();
int idBien = intent.getIntExtra("id_bien", 0);
int idEncuestaPreentrega = intent.getIntExtra("id_encuestapreentrega", 0);
String[][] arrayChequeoEncuesta = oDB.traerEncuestaPostventa(idBien,
idEncuestaPreentrega);
if(!(arrayChequeoEncuesta == null)){
for(int i=0; i<arrayChequeoEncuesta.length; i++){
int idEncuestaPostventa = Integer.parseInt(arrayChequeoEncuesta[i][0]);
int idEncuestaDetalle = Integer.parseInt(arrayChequeoEncuesta[i][1]);
String item = arrayChequeoEncuesta[i][2];
Boolean recepcion = (Integer.parseInt(arrayChequeoEncuesta[i][3]) != 0);
String observacion =arrayChequeoEncuesta[i][4];
listaChequeoEncuesta.add(new EncuestaPostventa(idEncuestaPostventa,
idEncuestaDetalle,
item,
recepcion,
observacion));
}
}
adapter = new EncuestaPostventaAdapter(this, listaChequeoEncuesta);
lvChequeoEncuesta = (ListView) findViewById(R.id.lvChequeoEncuesta);
lvChequeoEncuesta.setAdapter(adapter);
}catch(Exception e){
Toast.makeText(this, "Error (listarChequeoEncuesta): " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void listarConsumoBien(){
try{
oDB = new DBProvider(this);
Intent intent = getIntent();
int argIdBien = intent.getIntExtra("id_bien", 0);
int argIdEmpsa = intent.getIntExtra("id_empsa", 0);
String[][] arrayConsumoBien = oDB.traerConsumoBien(argIdBien,
argIdEmpsa);
if(!(arrayConsumoBien == null)){
for(int i=0; i<arrayConsumoBien.length; i++){
int idConsumoBien = Integer.parseInt(arrayConsumoBien[i][0]);
int idBien = Integer.parseInt(arrayConsumoBien[i][1]);
int idDominio = Integer.parseInt(arrayConsumoBien[i][2]);
String nombre = arrayConsumoBien[i][3];
String unidad = arrayConsumoBien[i][4];
int cantidad = Integer.parseInt(arrayConsumoBien[i][5]);
Boolean estado = (Integer.parseInt(arrayConsumoBien[i][6]) != 0);
listaConsumoBien.add(new ConsumoBien(idConsumoBien,
idBien,
idDominio,
nombre,
unidad,
cantidad,
estado));
}
}
adapterConsumoBien = new ConsumoBienAdapter(this, listaConsumoBien);
lvConsumoBien = (ListView) findViewById(R.id.lvConsumoBien);
lvConsumoBien.setAdapter(adapterConsumoBien);
}catch(Exception e){
Toast.makeText(this, "Error (listarConsumoBien): " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
public void onNothingSelected(AdapterView<?> parent)
{
}
}
And its layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:parentActivityName="net.gestionwireless.officemovil.inmobiliario.PostventaPreentregaActivity">
<TabHost android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelProyecto"
android:text="#string/proyecto"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvProyecto"
android:text=""
android:layout_toRightOf="#id/tvLabelProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelRut"
android:layout_below="#id/tvLabelProyecto"
android:text="#string/rut"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvRut"
android:text=""
android:layout_toRightOf="#id/tvLabelRut"
android:layout_below="#id/tvProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelCliente"
android:layout_marginLeft="50dp"
android:layout_below="#id/tvLabelProyecto"
android:layout_toRightOf="#id/tvRut"
android:text="#string/cliente" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvCliente"
android:text=""
android:layout_toRightOf="#id/tvLabelCliente"
android:layout_below="#id/tvProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelDireccion"
android:layout_below="#id/tvCliente"
android:text="#string/direccion"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvDireccion"
android:text=""
android:layout_toRightOf="#id/tvLabelDireccion"
android:layout_below="#id/tvCliente" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tvDireccion">
<TabWidget android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs" />
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent">
<LinearLayout
android:id="#+id/tabChequeo"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:text="#string/titulo_grilla_item"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_recepcion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_observacion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".57"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lvChequeoEncuesta"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
</LinearLayout>
<LinearLayout
android:id="#+id/tabServicios"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:text="#string/titulo_grilla_servicio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".4"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_recepcion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_consumo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_unidad"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".2"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lvConsumoBien"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
</LinearLayout>
<LinearLayout android:id="#+id/tabObservaciones"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/etObservaciones"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hint_observaciones" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</TabHost>
</LinearLayout>
The class for each item:
package net.gestionwireless.officemovil.inmobiliario;
public class EncuestaPostventa {
private int idEncuestaPostventa;
private int idEncuestaDetalle;
private String item;
private Boolean recepcion;
private String observacion;
public EncuestaPostventa(int idEncuestaPostventa,
int idEncuestaDetalle,
String item,
Boolean recepcion,
String observacion) {
this.idEncuestaPostventa = idEncuestaPostventa;
this.idEncuestaDetalle = idEncuestaDetalle;
this.item = item;
this.recepcion = recepcion;
this.observacion = observacion;
}
public int traerIdEncuestaPostventa() {
return idEncuestaPostventa;
}
public void asignarIdEncuestaPostventa(int idEncuestaPostventa) {
this.idEncuestaPostventa = idEncuestaPostventa;
}
public int traerIdEncuestaDetalle() {
return idEncuestaDetalle;
}
public void asignarIdEncuestaDetalle(int idEncuestaDetalle) {
this.idEncuestaDetalle = idEncuestaDetalle;
}
public String traerItem() {
return item;
}
public void asignarItem(String item) {
this.item = item;
}
public Boolean traerRecepcion() {
return recepcion;
}
public void asignarRecepcion(Boolean recepcion) {
this.recepcion = recepcion;
}
public String traerObservacion() {
return observacion;
}
public void asignarObservacion(String observacion) {
this.observacion = observacion;
}
}
package net.gestionwireless.officemovil.inmobiliario;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
The adapter:
public class EncuestaPostventaAdapter extends ArrayAdapter<EncuestaPostventa> {
private Context context;
private ArrayList<EncuestaPostventa> datos;
public EncuestaPostventaAdapter(Context context, ArrayList<EncuestaPostventa> datos) {
super(context, R.layout.encuestapostventa_item, datos);
this.context = context;
this.datos = datos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = LayoutInflater.from(context).inflate(
R.layout.encuestapostventa_item, null);
TextView tvItem = (TextView) item.findViewById(R.id.tvItem);
tvItem.setText(datos.get(position).traerItem());
CheckBox chkRecepcion = (CheckBox) item.findViewById(R.id.chkRecepcion);
chkRecepcion.setChecked(datos.get(position).traerRecepcion());
EditText editObservacion = (EditText) item.findViewById(R.id.editObservacion);
editObservacion.setText(datos.get(position).traerObservacion());
return item;
}
}
And the layout for each item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="horizontal">
<TextView
android:id="#+id/tvItem"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".33"
android:textSize="#dimen/texto_L" />
<CheckBox
android:id="#+id/chkRecepcion"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".1"/>
<EditText
android:id="#+id/editObservacion"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".57"
android:textSize="#dimen/texto_L"
android:inputType="textCapSentences" />
</LinearLayout>
If you put a log statement in your ArrayAdapter.getView(), you'll realize what's going on in two seconds.
As the list is scrolled, a list item that you edited is scrolled out of view. When the item is scrolled back into view, the view is recreated and getView() is called. Since your adapter doesn't have a representation of the changes that were made previously, getView() recreates the view with the original unedited data.
If that's happening to you on focus lost, that must mean that the focus-lost event is triggering a view update on the list item. I've never done editing in a list item, so I'm not familiar with that behavior.
You need to put event listeners on your EditText and CheckBox that store their edited state somewhere. Then your adapter needs to use that edit state when creating the list items.
You might have to write a more complex adapter that extends BaseAdapter directly. The adapter is the Model for your list View, and there's no state in a ListView except for your adapter. In the case of ListView, the view can update any part of its list at any time, so the adapter has to have the current model data for the ListView at all times.

Categories

Resources