ViewPager not responding to touch in layout area created dynamically in Fragment - android

I'm trying to implement Viewpager with a calendar. I'm using the same three instances of the calendar Fragment for testing the ViewPager lets call the smooth motion of transferring one fragment to the next SWIPING. the swiping will not work in the area of the fragment that the layout was created dynamically in the fragment itself but the rest of page(above and below the date buttons)the swiping works great! here is some of the code the entire frag code would not fit so had to edit some declarations and button listener methods
// Main Activity
public class calenderview extends AppCompatActivity {
ArrayList<Fragment> fraglist;
ViewPager pager;
calenderviewpageradaptor adaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calenderview);
fraglist = new ArrayList<>();
fraglist.add(new Calview_frag()); fraglist.add(new Calview_frag()); fraglist.add(new Calview_frag());
adaptor = new calenderviewpageradaptor(getSupportFragmentManager(),fraglist);
pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adaptor);
}
public class calenderviewpageradaptor extends FragmentStatePagerAdapter {
ArrayList<Fragment> adaptorlist;
public calenderviewpageradaptor(FragmentManager fm,ArrayList<Fragment> list){
super (fm);
this.adaptorlist = list;
}
#Override
public int getCount(){
return 3;
}
#Override
public Fragment getItem(int pos){
return adaptorlist.get(pos);
}
}
}
public class Calview_frag extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private LinearLayout.LayoutParams getdaysLayoutParams() {
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
return buttonParams;
}
private void addDaysinCalendar(ViewGroup.LayoutParams buttonParams, DisplayMetrics metrics) {
int engDaysArrayCounter = 0;
LinearLayout.LayoutParams doitwithmarg = new LinearLayout.LayoutParams(120,120);
doitwithmarg.setMarginStart(cacmarg);
LinearLayout.LayoutParams doittoit = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
doittoit.weight=1;
for (int weekNumber = 0; weekNumber < 6; ++weekNumber) {
for (int dayInWeek = 0; dayInWeek < 7; ++dayInWeek) {
Button day = new Button(getContext());
day.setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
day.setTextColor(getResources().getColor(R.color.GREY));
day.setBackgroundColor(Color.TRANSPARENT);
day.setTextSize((int) metrics.density *5 );
day.setSingleLine();
if(dayInWeek!=0){
day.setLayoutParams(doitwithmarg);
Space s = new Space(getContext());
s.setLayoutParams(doittoit);
weeks[weekNumber].addView(s);
days[engDaysArrayCounter] = day;
weeks[weekNumber].addView(day);}
else{
day.setLayoutParams(doitwithmarg);
days[engDaysArrayCounter] = day;
weeks[weekNumber].addView(day);}
++engDaysArrayCounter;
}
}
}
private void init(View view) {
DisplayMetrics metrics = getResources().getDisplayMetrics();
calendar = Calendar.getInstance();
weekOneLayout = (LinearLayout)view.findViewById(R.id.calendar_week_1);
weekTwoLayout = (LinearLayout)view.findViewById(R.id.calendar_week_2);
weekThreeLayout = (LinearLayout)view.findViewById(R.id.calendar_week_3);
weekFourLayout = (LinearLayout)view.findViewById(R.id.calendar_week_4);
weekFiveLayout = (LinearLayout)view.findViewById(R.id.calendar_week_5);
weekSixLayout = (LinearLayout)view.findViewById(R.id.calendar_week_6);
currentYear = (TextView)view.findViewById(R.id.current_date);
currentMonth = (TextView)view.findViewById(R.id.current_month);
currentDateDay = chosenDateDay = calendar.get(Calendar.DAY_OF_MONTH);
if (userMonth != 0 && userYear != 0) {
currentDateMonth = chosenDateMonth = userMonth;
currentDateYear = chosenDateYear = userYear;
} else {
currentDateMonth = chosenDateMonth = calendar.get(Calendar.MONTH);
currentDateYear = chosenDateYear = calendar.get(Calendar.YEAR);
}
currentYear.setText("" + chosenDateYear);
currentMonth.setText(ENG_MONTH_NAMES[currentDateMonth]);
initializeDaysWeeks();
if (userButtonParams != null) {
defaultButtonParams = userButtonParams;
} else {
defaultButtonParams = getdaysLayoutParams();
}
addDaysinCalendar(defaultButtonParams,metrics);
initCalendarWithDate(chosenDateYear, chosenDateMonth, chosenDateDay,view);
}
private void initializeDaysWeeks() {
weeks = new LinearLayout[6];
days = new Button[6 * 7];
weeks[0] = weekOneLayout;
weeks[1] = weekTwoLayout;
weeks[2] = weekThreeLayout;
weeks[3] = weekFourLayout;
weeks[4] = weekFiveLayout;
weeks[5] = weekSixLayout;
}
private void initCalendarWithDate(int year, int month, int day, View v) {
if (calendar == null)
calendar = Calendar.getInstance();
calendar.set(year, month, day);
int daysInCurrentMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
chosenDateYear = year;
chosenDateMonth = month;
chosenDateDay = day;
calendar.set(year, month, 1);
int firstDayOfCurrentMonth = calendar.get(Calendar.DAY_OF_WEEK);
Log.d(tag,"FFFFFFiiiiiiiiiiirrrrrrrrrrsssssssssst day of month int"+firstDayOfCurrentMonth);
calendar.set(year, month, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Log.d(tag,"LLLLLLLLLLLLlaaaaasttttttttttt day of month int"+daysInCurrentMonth);
int dayNumber = 1;
int daysLeftInFirstWeek = 0;
firstDayOfCurrentMonth= firstDayOfCurrentMonth-1;
int indexOfDayAfterLastDayOfMonth = 0;
if (firstDayOfCurrentMonth != 0) {
daysLeftInFirstWeek = firstDayOfCurrentMonth;
indexOfDayAfterLastDayOfMonth = daysLeftInFirstWeek + daysInCurrentMonth;
> for (int i = firstDayOfCurrentMonth; i < firstDayOfCurrentMonth + daysInCurrentMonth; ++i) {
//checks all dates of calendar to set background and text colors
if (currentDateMonth == chosenDateMonth
&& currentDateYear == chosenDateYear
&& dayNumber == currentDateDay){
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapegrey));
days[i].setTextColor(Color.WHITE);
} else {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
days[i].setTextColor(Color.BLACK);
}
int[] dateArr = new int[3];
dateArr[0] = dayNumber;
dateArr[1] = chosenDateMonth;
dateArr[2] = chosenDateYear;
days[i].setTag(dateArr);
days[i].setText(String.valueOf(dayNumber));
days[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDayClick(v);
}
});
++dayNumber;
}
>
for (int i = 7; i < 7 + daysInCurrentMonth; ++i) {
if (currentDateMonth == chosenDateMonth
&& currentDateYear == chosenDateYear
&& dayNumber == currentDateDay) {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshape));
days[i].setTextColor(Color.WHITE);
} else {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
days[i].setTextColor(Color.BLACK);
}
int[] dateArr = new int[3];
dateArr[0] = dayNumber;
dateArr[1] = chosenDateMonth;
dateArr[2] = chosenDateYear;
days[i].setTag(dateArr);
days[i].setText(String.valueOf(dayNumber));
days[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onDayClick(v);
}
});
++dayNumber;
}
}
//Displays previous and next month days
if (month > 0)
calendar.set(year, month - 1, 1);
else
calendar.set(year - 1, 11, 1);
int daysInPreviousMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = daysLeftInFirstWeek - 1; i >= 0; --i) {
int[] dateArr = new int[3];
if (chosenDateMonth > 0) {
if (currentDateMonth == chosenDateMonth - 1
&& currentDateYear == chosenDateYear
&& daysInPreviousMonth == currentDateDay) {
} else {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
}
dateArr[0] = daysInPreviousMonth;
dateArr[1] = chosenDateMonth - 1;
dateArr[2] = chosenDateYear;
} else {
if (currentDateMonth == 11
&& currentDateYear == chosenDateYear - 1
&& daysInPreviousMonth == currentDateDay) {
} else {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
}
dateArr[0] = daysInPreviousMonth;
dateArr[1] = 11;
dateArr[2] = chosenDateYear - 1;
}
days[i].setTag(dateArr);
days[i].setTextColor(getResources().getColor(R.color.GREY));;
days[i].setText("");
days[i].setOnClickListener(null);
}
int nextMonthDaysCounter = 1;
for (int i = indexOfDayAfterLastDayOfMonth; i < days.length; ++i) {
int[] dateArr = new int[3];
if (chosenDateMonth < 11) {
if (currentDateMonth == chosenDateMonth + 1
&& currentDateYear == chosenDateYear
&& nextMonthDaysCounter == currentDateDay) {
// days[i].setBackground(getResources().getDrawable(R.drawable.roundshapegrey));
days[i].setTextColor(Color.WHITE);
} else {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
}
dateArr[0] = nextMonthDaysCounter;
dateArr[1] = chosenDateMonth + 1;
dateArr[2] = chosenDateYear;
} else {
if (currentDateMonth == 0
&& currentDateYear == chosenDateYear + 1
&& nextMonthDaysCounter == currentDateDay) {
// selectedDayButton.setBackground(getResources().getDrawable(R.drawable.roundshapegrey));
selectedDayButton.setTextColor(Color.WHITE);
// days[i].setBackground(getResources().getDrawable(R.drawable.roundshapegrey));
days[i].setTextColor(Color.WHITE);
} else {
days[i].setBackground(getResources().getDrawable(R.drawable.roundshapeclear));
}
dateArr[0] = nextMonthDaysCounter;
dateArr[1] = 0;
dateArr[2] = chosenDateYear + 1;
}
days[i].setTag(dateArr);
days[i].setText("");
days[i].setOnClickListener(null);
}
calendar.set(chosenDateYear, chosenDateMonth, chosenDateDay);
currentYear.setText(" " + chosenDateYear);
currentMonth.setText(ENG_MONTH_NAMES[chosenDateMonth]);
}
public Calview_frag() {//required empty constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layoutview = inflater.inflate(R.layout.fragment_calview,container,false);
but = (ImageButton)layoutview.findViewById(R.id.getitbutton);
fbut = (ImageButton)layoutview.findViewById(R.id.getit2button);
display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenheight = size.y;
screenwidth = size.x;
Log.d(tag,"sssssssssssccreen size "+screenwidth);
if(screenwidth<1300)
cacmarg = screenwidth/50;
else
cacmarg = screenwidth/25;
init(layoutview);
return layoutview;
}
}
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/getitbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_alignParentLeft="true"
android:src="#drawable/backbutton"
tools:layout_editor_absoluteY="0dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/current_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/bluegrey"
android:textSize="28sp" />
<TextView
android:id="#+id/current_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:textColor="#color/bluegrey"
android:textSize="28sp" />
</LinearLayout>
<ImageButton
android:id="#+id/getit2button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/forwardbutton"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7">
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/sunday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/monday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
<Button
android:id="#+id/button10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/tuesday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
<Button
android:id="#+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/wednesday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
<Button
android:id="#+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/thursday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/friday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/transparent"
android:text="#string/saturday"
android:textColor="#color/bluegrey"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/calendar_week_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7" />
<LinearLayout
android:id="#+id/calendar_week_2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7" />
<LinearLayout
android:id="#+id/calendar_week_3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7" />
<LinearLayout
android:id="#+id/calendar_week_4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7" />
<LinearLayout
android:id="#+id/calendar_week_5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7" />
<LinearLayout
android:id="#+id/calendar_week_6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7" /> </LinearLayout>
</ScrollView>
</LinearLayout>

are you passing the instance of the Fragment to the adapter? No I think. You should pass the list of fragments to the adapter along with fragment manager and should also change the calendarViewPager accordingly.
List<Fragment> fragments =new ArrayList<>();
fragments.add(Calview_frag());
fragments.add(Calview_frag());
fragments.add(Calview_frag());
calenderviewpageradaptor adaptor =
new calenderviewpageradaptor(getSupportFragmentManager(),fragments);

Related

How to select a Bar / value when the graph is rolling (something like samsung health trends chart) using mpandroidchart

I want to make chart like samsung health, support scrolling and center selected item. I'm using this library https://github.com/PhilJay/MPAndroidChart . But only works in tap, I don't have any idea how to configure it for scrolling.
I want something like this (look at black circle) :
Samsung Health Chart
Url Video : https://www.youtube.com/watch?v=_rcJraCzdNw
Image :
Samsung chart, centered selected item when tap or scrolling
My Chart
But My Chart look like this.
Url Video : https://www.youtube.com/watch?v=ZQGj4CcBygU
Image :
My Chart, centered selected item when tap-only, not in scrolling.
I tried onChartGestureEnd() inside setOnGestureListener(), but the position x is the location my finger first touch the screen. Example: let's say i swipe right (left to right) my finger first touch is 18, and the center position will be item 14. I want get that item 14 position, but don't know how to do it. I thought deceleration, so I call stopDeceleration(), but not works.
I also tried with ViewPager but also failed :(
#Override
public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
MPPointD pointD = MPPointD.getInstance(0,0);
Transformer transformer = mChartOne.getTransformer(AxisDependency.LEFT);
transformer.getValuesByTouchPoint(me.getX(), me.getY(), pointD);
int roundX = round((float) pointD.x);
int roundY = round((float) pointD.y);
mChartOne.centerViewToAnimated(roundX, roundY, AxisDependency.LEFT, 200);
Utils.selectedIndex = roundX;
showSelectedInfo(roundX);
}
This is my code for this activity (Please ignore variable *Two) :
BarChartActivity.java
public class BarChartActivity extends AppCompatActivity {
private BarChart mChartOne;
private BarChart mChartTwo;
private Spinner mSpOption;
private TextView mTvDate;
private TextView mTvPower;
private TextView mTvCost;
private Legend lOne;
private Legend lTwo;
private LimitLine llOne;
private LimitLine llTwo;
private XAxis xAxisOne;
private XAxis xAxisTwo;
private YAxis leftAxisOne;
private YAxis leftAxisTwo;
private YAxis rightAxisOne;
private YAxis rightAxisTwo;
private ArrayList<BarEntry> barValuesOne = new ArrayList<>();
private ArrayList<BarEntry> barValuesTwo = new ArrayList<>();
private List<String> axisLabelOne = new ArrayList<>();
private List<String> axisLabelTwo = new ArrayList<>();
private List<Statistic> statisticList = new ArrayList<>();
private List<String> option = new ArrayList<>();
private String TAG = "bebe";
private String[] dummyCost;
private String[] dummyPower;
private String[] dummyDate;
private int lastIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_be_chart);
setTitle("BarChartActivity");
//todo : create another layout for different dpi
mChartOne = findViewById(R.id.chart1);
mChartTwo = findViewById(R.id.chart2);
mSpOption = findViewById(R.id.sp_option);
mTvDate = findViewById(R.id.tv_date);
mTvPower = findViewById(R.id.tv_power);
mTvCost = findViewById(R.id.tv_cost);
option.add("Days");
option.add("Week");
option.add("Month");
dummyCost = getResources().getStringArray(R.array.dummy_cost);
dummyDate = getResources().getStringArray(R.array.dummy_date);
dummyPower = getResources().getStringArray(R.array.dummy_power);
int lastNum = 0;
for (int i = 0; i < dummyPower.length; i++) {
Statistic stat = new Statistic();
stat.cost = dummyCost[i];
stat.date = dummyDate[i];
stat.power = dummyPower[i];
statisticList.add(stat);
String numberStr = stat.date.substring(8,10);
int numStr = Integer.parseInt(numberStr); // remove 0, 01 -> 1
axisLabelOne.add(String.valueOf(numStr));
lastNum = numStr;
}
// empty label
for (int i = 0; i < 3; i++) {
lastNum++;
if (lastNum > 31) lastNum = 1;
axisLabelOne.add(String.valueOf(lastNum));
}
axisLabelTwo = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.label_hour)));
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, option);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpOption.setAdapter(dataAdapter);
mSpOption.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
barValuesOne.clear();
mChartOne.animateY(500);
setDataOne();
mChartOne.setVisibleXRangeMaximum(7);
BarEntry lastEntry = barValuesOne.get(lastIndex);
Utils.selectedIndex = lastEntry.getX();
showSelectedInfo(lastIndex);
mChartOne.centerViewToAnimated(lastEntry.getX(), lastEntry.getY(),
AxisDependency.LEFT, 0);
mChartOne.invalidate();
barValuesTwo.clear();
mChartTwo.animateY(500);
setDataTwo();
mChartTwo.invalidate();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
loadChartOne();
loadChartTwo();
}
private void loadChartOne(){
mChartOne.setDrawBarShadow(false);
mChartOne.setDrawValueAboveBar(true);
mChartOne.getDescription().setEnabled(false);
mChartOne.setPinchZoom(false);
mChartOne.setDrawGridBackground(false);
mChartOne.setDragEnabled(true);
mChartOne.setScaleEnabled(false);
mChartOne.setPinchZoom(false);
mChartOne.setDoubleTapToZoomEnabled(false);
mChartOne.setDrawBorders(false);
mChartOne.setExtraOffsets(0f,
getResources().getDimensionPixelSize(R.dimen.padding_label),
0f,
getResources().getDimensionPixelSize(R.dimen.padding_label));
mChartOne.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
#Override
public void onValueSelected(Entry e, Highlight h) {
if (e == null)
return;
Log.e(TAG, "onValueSelected: "+e);
Log.e(TAG, "data: "+ axisLabelOne.get((int) e.getX()));
mChartOne.centerViewToAnimated(e.getX(), e.getY(),
mChartOne.getData().getDataSetByIndex(h.getDataSetIndex())
.getAxisDependency(), 200);
Utils.selectedIndex = e.getX();
showSelectedInfo((int) e.getX());
}
#Override
public void onNothingSelected() {
}
});
mChartOne.setOnChartGestureListener(new OnChartGestureListener() {
#Override
public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
}
#Override
public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
MPPointD pointD = MPPointD.getInstance(0,0);
Transformer transformer = mChartOne.getTransformer(AxisDependency.LEFT);
transformer.getValuesByTouchPoint(me.getX(), me.getY(), pointD);
int roundX = round((float) pointD.x);
int roundY = round((float) pointD.y);
mChartOne.centerViewToAnimated(roundX, roundY, AxisDependency.LEFT, 200);
Utils.selectedIndex = roundX;
showSelectedInfo(roundX);
}
#Override
public void onChartLongPressed(MotionEvent me) {
}
#Override
public void onChartDoubleTapped(MotionEvent me) {
}
#Override
public void onChartSingleTapped(MotionEvent me) {
}
#Override
public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {
}
#Override
public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
}
#Override
public void onChartTranslate(MotionEvent me, float dX, float dY) {
}
});
ValueFormatter xAxisFormatter = new IndexAxisValueFormatter(axisLabelOne);
xAxisOne = mChartOne.getXAxis();
xAxisOne.setPosition(XAxisPosition.BOTTOM);
xAxisOne.setTextSize(16f);
xAxisOne.setGranularity(1f); // only intervals of 1 day
xAxisOne.setLabelCount(7);
xAxisOne.setValueFormatter(xAxisFormatter);
xAxisOne.setDrawGridLines(false);
xAxisOne.setDrawAxisLine(false);
xAxisOne.customLabel = true;
xAxisOne.setYOffset(getResources().getDimensionPixelSize(R.dimen.padding_label));
ValueFormatter custom = new MyValueFormatter(" W");
leftAxisOne = mChartOne.getAxisLeft();
leftAxisOne.setLabelCount(8, false);
leftAxisOne.setValueFormatter(custom);
leftAxisOne.setPosition(YAxisLabelPosition.OUTSIDE_CHART);
leftAxisOne.setSpaceTop(15f);
leftAxisOne.setAxisMinimum(1f); // this replaces setStartAtZero(true)
leftAxisOne.setEnabled(false);
llOne = new LimitLine(16f, "Usage warning (16 W)");
llOne.setLineColor(Color.RED);
llOne.setLineWidth(1f);
llOne.setTextColor(Color.BLACK);
llOne.setTextSize(12f);
llOne.enableDashedLine(4, 3, 0);
rightAxisOne = mChartOne.getAxisRight();
rightAxisOne.setDrawGridLines(true);
rightAxisOne.setLabelCount(2, false);
rightAxisOne.setValueFormatter(custom);
rightAxisOne.setSpaceTop(15f);
rightAxisOne.setAxisMinimum(1f); // this replaces setStartAtZero(true)
rightAxisOne.setCenterAxisLabels(true);
rightAxisOne.setPosition(YAxisLabelPosition.INSIDE_CHART);
rightAxisOne.enableGridDashedLine(4, 3, 0);
rightAxisOne.setGridColor(ContextCompat.getColor(this, R.color.bar_color));
rightAxisOne.addLimitLine(llOne);
rightAxisOne.setDrawLimitLinesBehindData(false);
rightAxisOne.setDrawZeroLine(false);
rightAxisOne.setDrawAxisLine(false);
lOne = mChartOne.getLegend();
lOne.setEnabled(false);
}
private void loadChartTwo(){
mChartTwo.setDrawBarShadow(false);
mChartTwo.setDrawValueAboveBar(false);
mChartTwo.getDescription().setEnabled(false);
mChartTwo.setPinchZoom(false);
mChartTwo.setDrawGridBackground(false);
mChartTwo.setDragEnabled(false);
mChartTwo.setScaleEnabled(false);
mChartTwo.setPinchZoom(false);
mChartTwo.setDoubleTapToZoomEnabled(false);
mChartTwo.setDrawBorders(false);
mChartTwo.setExtraOffsets(0f,
getResources().getDimensionPixelSize(R.dimen.padding_label),
0f,
getResources().getDimensionPixelSize(R.dimen.padding_label));
MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
mv.setChartView(mChartTwo); // For bounds control
mChartTwo.setMarker(mv); // Set the marker to the chart
ValueFormatter xAxisFormatter = new IndexAxisValueFormatter(axisLabelTwo);
xAxisTwo = mChartTwo.getXAxis();
xAxisTwo.setPosition(XAxisPosition.BOTTOM);
xAxisTwo.setTextSize(10f);
xAxisTwo.setValueFormatter(xAxisFormatter);
xAxisTwo.setDrawGridLines(false);
xAxisTwo.setDrawAxisLine(true);
xAxisTwo.setLabelCount(5);
xAxisTwo.customLabel = false;
leftAxisTwo = mChartTwo.getAxisLeft();
leftAxisTwo.setAxisMinimum(1f);
leftAxisTwo.setEnabled(false);
rightAxisTwo = mChartTwo.getAxisRight();
rightAxisTwo.setAxisMinimum(1f);
rightAxisTwo.setEnabled(false);
lTwo = mChartTwo.getLegend();
lTwo.setEnabled(false);
}
private void setDataOne() {
// start empty space
Utils.unselectedIndex[0] = 0f;
Utils.unselectedIndex[1] = 1f;
Utils.unselectedIndex[2] = 2f;
Utils.firstSelectedIndex = 3f;
barValuesOne.add(new BarEntry(Utils.unselectedIndex[0], 0));
barValuesOne.add(new BarEntry(Utils.unselectedIndex[1], 0));
barValuesOne.add(new BarEntry(Utils.unselectedIndex[2], 0));
float start = Utils.firstSelectedIndex;
float tmpStart = start;
for (int i = (int) start; i < dummyPower.length; i++) {
tmpStart = i;
lastIndex = i;
float val = Float.parseFloat(dummyPower[i]);
barValuesOne.add(new BarEntry(i, val));
Utils.lastSelectedIndex = i;
}
// end empty space
barValuesOne.add(new BarEntry(++tmpStart, 0));
Utils.unselectedIndex[3] = tmpStart;
barValuesOne.add(new BarEntry(++tmpStart, 0));
Utils.unselectedIndex[4] = tmpStart;
barValuesOne.add(new BarEntry(++tmpStart, 0));
Utils.unselectedIndex[5] = tmpStart;
BarDataSet set1;
if (mChartOne.getData() != null &&
mChartOne.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) mChartOne.getData().getDataSetByIndex(0);
set1.setValues(barValuesOne);
mChartOne.getData().notifyDataChanged();
mChartOne.notifyDataSetChanged();
} else {
set1 = new BarDataSet(barValuesOne, "The year 2017");
set1.setDrawIcons(false);
set1.setColor(ContextCompat.getColor(this, R.color.bar_color));
set1.setHighLightColor(ContextCompat.getColor(this, R.color.bar_color));
ArrayList<IBarDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
data.setValueTextSize(8f);
data.setBarWidth(0.2f);
mChartOne.setData(data);
}
}
private void setDataTwo() {
float start = 0f;
int count = 24;
int range = 20;
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
for (int i = (int) start; i < start + count; i++) {
float val = (float) (Math.random() * (range + 1));
if (val < 4) val += 6.5;
if (i < hour) barValuesTwo.add(new BarEntry(i, val));
else barValuesTwo.add(new BarEntry(i, 0));
}
BarDataSet set1;
if (mChartTwo.getData() != null &&
mChartTwo.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) mChartTwo.getData().getDataSetByIndex(0);
set1.setValues(barValuesTwo);
set1.setDrawValues(false);
mChartTwo.getData().notifyDataChanged();
mChartTwo.notifyDataSetChanged();
} else {
set1 = new BarDataSet(barValuesTwo, "The year 2017");
set1.setDrawIcons(false);
set1.setDrawValues(false);
set1.setColor(ContextCompat.getColor(this, R.color.bar_hour_color));
set1.setHighLightColor(ContextCompat.getColor(this, R.color.bar_hour_color));
ArrayList<IBarDataSet> dataSets = new ArrayList<>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
data.setValueTextSize(12f);
data.setBarWidth(0.2f);
mChartTwo.setData(data);
}
}
private final RectF onValueSelectedRectF = new RectF();
private void showSelectedInfo(int position){
boolean unselected = false;
for (int i = 0; i < Utils.unselectedIndex.length; i++) {
if (position == Utils.unselectedIndex[i]) {
unselected = true;
break;
}
}
if (!unselected && position == Utils.selectedIndex) {
Statistic stat = statisticList.get(position);
setTextData(stat);
} else if (unselected){
if (position > Utils.lastSelectedIndex ||
position < Utils.firstSelectedIndex){
if ((position <= Utils.firstSelectedIndex)){
Statistic stat = statisticList.get((int) Utils.firstSelectedIndex);
setTextData(stat);
} else if ((position >= Utils.lastSelectedIndex)) {
Statistic stat = statisticList.get((int) Utils.lastSelectedIndex);
setTextData(stat);
}
}
}
}
private void setTextData(Statistic stat){
int cost = Integer.parseInt(stat.cost);
String thousandCost = NumberFormat.getNumberInstance(Locale.GERMAN).format(cost);
mTvDate.setText(getDateString(stat.date));
mTvPower.setText(stat.power + " W");
mTvCost.setText("(Rp "+thousandCost+")");
}
private String getDateString(String rawDate) {
String date = rawDate.replace("-","").substring(0, 8);
String year = date.substring(0,4);
String month = date.substring(4,6);
String day = date.substring(6,8);
String monthName = getMonthName(month);
return String.valueOf(new StringBuilder().append(day).append(" ").append(monthName)
.append(" ").append(year));
}
private String getMonthName(String data) {
int month = Integer.parseInt(data);
String[] monthName = {"Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli",
"Agustus", "September", "Oktober", "November", "Desember"};
return monthName[month-1];
}
public int round(float f) {
int c = (int) ((f) + 0.5f);
float n = f + 0.5f;
return (n - c) % 2 == 0 ? (int) f : c;
}
}
This is my layout :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_below="#id/chart1"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#e1e1e1"
android:layout_marginTop="-48dp"
android:layout_centerHorizontal="true">
<View
android:id="#+id/v_selected_label"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_centerInParent="true"
android:background="#drawable/selected_bar_label"/>
<View
android:id="#+id/v_tooltip"
android:layout_width="8dp"
android:layout_height="8dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:background="#drawable/tooltip"/>
</RelativeLayout>
<com.github.mikephil.charting.charts.BarChart
android:id="#+id/chart1"
android:layout_width="match_parent"
android:layout_height="240dp"
android:padding="0dp"
android:layout_marginTop="16dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:layout_marginBottom="0dp"/>
<Spinner
android:id="#+id/sp_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:background="#android:color/white"/>
</RelativeLayout>
<TextView
android:id="#+id/tv_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:textSize="16sp"
tools:text="24 Januari 2019" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="16dp"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_power"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
tools:text="27 W" />
<TextView
android:id="#+id/tv_cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginStart="8dp"
tools:text="(Rp 5000)" />
</LinearLayout>
<TextView
android:id="#+id/tv_last_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:text="#string/dummy_last_update" />
<com.github.mikephil.charting.charts.BarChart
android:id="#+id/chart2"
android:layout_width="match_parent"
android:layout_height="240dp"
android:padding="0dp"
android:layout_marginTop="16dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:layout_marginBottom="0dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="16dp"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:text="#string/label"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="8dp"
android:textColor="#android:color/black"
android:text="#string/power_plug"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_marginTop="8dp"
android:src="#drawable/underline_statistic"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginTop="16dp"
android:text="#string/total_time"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="8dp"
android:textColor="#android:color/black"
android:text="#string/dummy_total_time"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_marginTop="8dp"
android:src="#drawable/underline_statistic"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
I expect my chart support for scrolling too, not only tap.

Align images and text with GridView

I have the following design.
As you can see, the week days text and the "column title" images are not aligned to the GridView items.
Here is the complete xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="11"
tools:context="com.test.me.fragments.patientResume">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:background="#drawable/gradient">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/aboveLights"
android:src="#mipmap/above_lights"
android:contentDescription="#string/above_lights" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#mipmap/under_lights"
android:contentDescription="#string/under_lights" />
<com.test.dashboard.view.CircleImageView
android:id="#+id/centerImg"
android:layout_width="104dp"
android:layout_height="104dp"
android:layout_centerInParent="true"
android:background="#mipmap/ic_default_avatar" />
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/PatientName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/aboveLights"
android:layout_alignTop="#id/aboveLights"
android:layout_alignRight="#id/aboveLights"
android:layout_alignBottom="#id/aboveLights"
android:layout_margin="1dp"
android:gravity = "center_horizontal"
android:textSize="20sp"
android:text="Mauricio Affonso"
android:textColor="#color/colorPrimaryDark" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="25dp">
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/took_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/took"
android:textColor="#color/colorPrimaryDark" />
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/took_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/took_header"
android:gravity="center"
android:text="-"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp">
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/missed_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/missed"
android:textColor="#color/colorPrimaryDark" />
<com.test.dashboard.view.widget.RobotoLightTextView
android:id="#+id/missed_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/missed_header"
android:layout_alignRight="#+id/missed_header"
android:layout_below="#+id/missed_header"
android:gravity="center"
android:text="-"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
</RelativeLayout>
<com.test.me.wave.WavesView
android:id="#+id/waves_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#ddf7ff">
<com.test.dashboard.view.widget.RobotoLightTextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/countPatient"
android:textAlignment="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimaryDark"
android:text="1 OF 1"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/titleImages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/backgroundLight">
<ImageView
android:id="#+id/morning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:scaleType="fitCenter"
android:src="#mipmap/ic_morning" />
<ImageView
android:id="#+id/noon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:src="#mipmap/ic_noon" />
<ImageView
android:id="#+id/evening"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:src="#mipmap/ic_evening" />
<ImageView
android:id="#+id/bedtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="30dp"
android:maxHeight="30dp"
android:src="#mipmap/ic_bedtime" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="7"
android:id="#+id/tableContainer"
android:background="#color/backgroundLight">
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/date_layout"
android:layout_margin="#dimen/activity_horizontal_margin"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" />
<com.test.me.grid.DateLayout
android:id="#+id/date_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="30dp"
android:id="#+id/Sun"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:text="SUN" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="75dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Mon"
android:text="MON" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="120dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Tue"
android:text="TUE" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="167dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Wed"
android:text="WED" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="215dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Thu"
android:text="THU" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="260dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Fri"
android:text="FRI" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/grid"
android:layout_marginTop="310dp"
android:textColor="#color/colorPrimaryDark"
android:layout_marginLeft="7dp"
android:id="#+id/Sat"
android:text="SAT" />
</RelativeLayout>
</LinearLayout>
As you can see the content of RelativeLayout titleImages and the week days text should be aligned to the GridView items but i'm having different results on different phone resolutions. I even tried to dynamically change the positions:
int test[] = new int[2];
int space = grid.getHorizontalSpacing();
int height = grid.getMeasuredHeight() / 7;
int Width = grid.getColumnWidth() / 2;
int paddingTop = grid.getPaddingTop();
int paddingLeft = grid.getPaddingLeft();
Resources r = getResources();
float spacePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, space + 10, r.getDisplayMetrics()) ;
float paddingTopPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingTop - 7, r.getDisplayMetrics());
float paddingLeftPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingLeft - 12, r.getDisplayMetrics());
grid.getLocationInWindow(test);
for(int i = 0; i < 7; i++){
Days[i].setY(paddingTopPx + (test[1] - grid.getMeasuredHeight()) + ((i +1)* (height)));
}
for(int i = 0; i < 4; i++){
icons[i].setX((paddingLeftPx + test[0]) + (i) * (spacePx + Width));
}
I checked with different layout but all seems not that perfect so the best way to make your view is use single gridview .Almost succeded but you have to work on that more logic to get exactly what you need
<GridView
android:id="#+id/grid_calender"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:numColumns="5"
android:verticalSpacing="0dp" />
day_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="5dp">
<TextView
android:id="#+id/tv_new"
android:layout_width="#dimen/text_height_width"
android:layout_height="#dimen/text_height_width"
android:layout_centerInParent="true"
android:gravity="center"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/darker_gray" />
</RelativeLayout>
Create adapter with a better logic as needed its an edited code,Please ignore the commented codes Thanks
public class CustomCalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK = 0;
public ArrayList<Day> dayList = new ArrayList<>();
String[] days;
Context context;
List<Boolean> event_status;
// Calendar local_cal_30 = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
Calendar cal;
public CustomCalendarAdapter(Context context, ArrayList<Day> dayList, List<Boolean> _event_status, Calendar cal) {
this.context = context;
this.dayList = dayList;
this.event_status = _event_status;
this.cal = cal;
cal.set(Calendar.DAY_OF_MONTH, 1);
refreshDays();
}
#Override
public int getCount() {
return days.length;
}
#Override
public Object getItem(int position) {
return dayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// public int getPrevMonth(){
// if(cal.get(Calendar.MONTH) == cal.getActualMinimum(Calendar.MONTH)){
// cal.set(Calendar.YEAR, cal.get(Calendar.YEAR-1));
// }else{
//
// }
// int month = cal.get(Calendar.MONTH);
// if(month == 0){
// return month = 11;
// }
//
// return month-1;
// }
public int getMonth() {
return cal.get(Calendar.MONTH);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position % 5 == 0) {
v = vi.inflate(R.layout.day_view, null);
TextView day = (TextView) v.findViewById(R.id.tv_new);
if (position / 5 == 0) {
day.setText(R.string.sunday);
} else if (position / 5 == 1) {
day.setText(R.string.monday);
} else if (position / 5 == 2) {
day.setText(R.string.tuesday);
} else if (position / 5 == 3) {
day.setText(R.string.wednesday);
} else if (position / 5 == 4) {
day.setText(R.string.thursday);
} else if (position / 5 == 5) {
day.setText(R.string.friday);
} else if (position / 5 == 6) {
day.setText(R.string.saturday);
}
} else {
Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
Day dayObject = dayList.get(position);
v = vi.inflate(R.layout.day_view, null);
// RelativeLayout rl_outerView = (RelativeLayout) v.findViewById(R.id.rl);
// FrameLayout today = (FrameLayout) v.findViewById(R.id.today_frame);
// FrameLayout event = (FrameLayout) v.findViewById(R.id.event_frame);
// FrameLayout disable_frame = (FrameLayout) v.findViewById(R.id.disable_frame);
// FrameLayout selected_frame = (FrameLayout) v.findViewById(R.id.selected_frame);
TextView tv_date = (TextView) v.findViewById(R.id.tv_new);
Calendar local_cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
tv_date.setVisibility(View.VISIBLE);
// rl_outerView.setVisibility(View.VISIBLE);
// selected_frame.setVisibility(View.GONE);
if (dayObject.getDay() == 0) {
// rl_outerView.setVisibility(View.GONE);
} else {
tv_date.setVisibility(View.VISIBLE);
tv_date.setText(String.valueOf(dayObject.getDay()));//sets the date
}
//Only show 30 days from current date
// if ((dayObject.getDay()<local_cal.get(Calendar.DAY_OF_MONTH) &&
// dayObject.getMonth() == local_cal.get(Calendar.MONTH)) || ((dayObject.getMonth() == local_cal_30.get(Calendar.MONTH))&&
// dayObject.getDay()>local_cal_30.get(Calendar.DAY_OF_MONTH))) {
//Only show upcoming dates from current date
if ((dayObject.getDay() < local_cal.get(Calendar.DAY_OF_MONTH) &&
dayObject.getMonth() == local_cal.get(Calendar.MONTH))) {
//These dates come out of 30 days(Based on current date)
// disable_frame.setVisibility(View.VISIBLE);
} else {
//Rest days come here
// disable_frame.setVisibility(View.GONE);
dayObject.setDisable_date(true);
// event.setVisibility(View.GONE);
tv_date.setTextColor(Color.WHITE);
//Now compare the schedule date list with each date for matches
for (int i = 0; i < CustomGridCalendarView.schedule_list.size(); i++) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date scheduleDate = format.parse(CustomGridCalendarView.schedule_list.get(i).getScheduleDate());
cal = Calendar.getInstance();
cal.setTime(scheduleDate);
if (dayObject.getDay() == cal.get(Calendar.DAY_OF_MONTH) &&
dayObject.getMonth() == cal.get(Calendar.MONTH) &&
dayObject.getYear() == cal.get(Calendar.YEAR)
) {
//Show the event frame, here we got a match date
// event.setVisibility(View.VISIBLE);
// today.setVisibility(View.GONE);
tv_date.setTextColor(context.getResources().getColor(R.color.colorPrimary));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
if (dayObject.isEvent_status()) {
// event.setVisibility(View.GONE);
// selected_frame.setVisibility(View.VISIBLE);
// today.setVisibility(View.GONE);
tv_date.setTextColor(Color.WHITE);
} else {
// selected_frame.setVisibility(View.GONE);
tv_date.setTextColor(Color.WHITE);
}
//Check for current date
if (dayObject.getYear() == local_cal.get(Calendar.YEAR) && dayObject.getMonth() == local_cal.get(Calendar.MONTH)
&& dayObject.getDay() == local_cal.get(Calendar.DAY_OF_MONTH)) {
// today.setVisibility(View.VISIBLE);
// tv_date.setTextColor(Color.WHITE);
// event.setVisibility(View.GONE);
// tv_date.setTypeface(Typeface.DEFAULT_BOLD);
} else {
// today.setVisibility(View.GONE);
}
}
}
return v;
}
public void refreshDays() {
boolean before_current_date = true;
// clear items
dayList.clear();
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH) + 7;
int firstDay = (int) cal.get(Calendar.DAY_OF_WEEK);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
//TimeZone tz = TimeZone.getDefault();
// figure size of the array
if (firstDay == 0) {
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 > 0) {
for (j = 0; j < (firstDay - FIRST_DAY_OF_WEEK) + 7; j++) {
days[j] = "";
Day d = new Day(0, 0, 0, false);
dayList.add(d);
}
} else {
for (j = 0; j < (FIRST_DAY_OF_WEEK * 6) + 7; j++) {
days[j] = "";
Day d = new Day(0, 0, 0, false);
dayList.add(d);
}
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
if (j > 0 && dayList.size() > 0 && j != 1) {
dayList.remove(j - 1);
}
for (int x = 0, i = j - 1; i < days.length; i++) {
Day day;
if (event_status.size() > x) {
day = new Day(dayNumber, year, month, event_status.get(x));
} else {
day = new Day(dayNumber, year, month, false);
}
x++;
Calendar cTemp = Calendar.getInstance();
cTemp.set(year, month, dayNumber);
//int startDay = Time.getJulianDay(cTemp.getTimeInMillis(), TimeUnit.MILLISECONDS.toSeconds(tz.getOffset(cTemp.getTimeInMillis())));
days[i] = "" + dayNumber;
dayNumber++;
dayList.add(day);
}
}
}

AppCompat-styled Rangebar (Seekbar with two Thumbs)

I found a couple of questions regarding rangebars (seekbars with two thumbs) on Android, like Android Seekbar with two thumbs or working with SeekBar with two thumbs. All the answers point to components that look quite outdated since Material Design and thus AppCompat was released.
What I'm looking for is a Rangebar that looks like the AppCompatSeekBar with two thumbs. Are there any available libraries or ways to hack into the platform SeekBar so that the available resources can be reused?
This is my first time answering something here.
I created my own custom rangebar as follows.
Create the following files.
RangeBar.java
public class RangeBar extends FrameLayout{
int minVal = 0;
int maxVal = 100;
Context context;
ImageView leftThumb;
ImageView rightThumb;
View view;
int leftThumbPos = 0;
int rightThumbPos = 100;
public RangeBar(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.view = inflate(getContext(), R.layout.range_seekbar, null);
addView(this.view);
}
public RangeBar(Context context){
super(context);
this.context = context;
this.view = inflate(getContext(), R.layout.range_seekbar, null);
addView(this.view);
}
public void create() {
leftThumb = (ImageView)findViewById(R.id.left_thumb);
rightThumb = (ImageView)findViewById(R.id.right_thumb);
final View leftBar = findViewById(R.id.left_bar);
final View rightBar = findViewById(R.id.right_bar);
final View middleBar = findViewById(R.id.middle_bar);
final LinearLayout.LayoutParams leftBarLayoutParams = (LinearLayout.LayoutParams) leftBar.getLayoutParams();
final LinearLayout.LayoutParams rightBarLayoutParams = (LinearLayout.LayoutParams) rightBar.getLayoutParams();
final LinearLayout.LayoutParams middleBarLayoutParams = (LinearLayout.LayoutParams) middleBar.getLayoutParams();
final LinearLayout llRangeSeekbar = (LinearLayout)findViewById(R.id.ll_range_seekbar);
((TextView)findViewById(R.id.tv_range_max)).setText(maxVal+"");
((TextView)findViewById(R.id.tv_range_min)).setText(minVal+"");
leftThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_min)).getText()+"");
rightThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_max)).getText()+"");
leftThumb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int diff = maxVal - minVal;
if(diff < 0){
diff = 100;
minVal = 0;
maxVal = 100;
}
float width = llRangeSeekbar.getWidth();
float gap = leftThumb.getWidth();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
leftThumb.bringToFront();
return true;
}else if (event.getAction() == MotionEvent.ACTION_MOVE ) {
float temp1 = leftBarLayoutParams.weight;
float temp2 = middleBarLayoutParams.weight;
leftBarLayoutParams.weight += event.getX()/width;
middleBarLayoutParams.weight = 1 - (leftBarLayoutParams.weight + rightBarLayoutParams.weight);
int tempMaxVal = Integer.parseInt(((TextView)findViewById(R.id.tv_range_max)).getText()+"");
int tempMinVal = (int)(diff*leftBarLayoutParams.weight + minVal);
if(tempMinVal > tempMaxVal){
tempMinVal = tempMaxVal;
}
if(tempMinVal < minVal){
tempMinVal = minVal;
}
((TextView)findViewById(R.id.tv_range_min)).setText(tempMinVal + "");
if(middleBarLayoutParams.weight > gap/width && leftBarLayoutParams.weight >= 0){
leftBar.setLayoutParams(leftBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}else {
if(leftBarLayoutParams.weight < 0){
leftBarLayoutParams.weight = 0;
middleBarLayoutParams.weight = 1 - (rightBarLayoutParams.weight + leftBarLayoutParams.weight);
}else{
middleBarLayoutParams.weight = gap/width + (tempMaxVal - tempMinVal)/(1.0f*diff);
leftBarLayoutParams.weight = 1 - (middleBarLayoutParams.weight + rightBarLayoutParams.weight);
}
leftBar.setLayoutParams(leftBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
leftThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_min)).getText()+"");
return true;
}else
{
return false;
}
}
});
rightThumb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int diff = maxVal - minVal;
if(diff < 0){
diff = 100;
minVal = 0;
maxVal = 100;
}
float width = llRangeSeekbar.getWidth();
float gap = leftThumb.getWidth();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rightThumb.bringToFront();
return true;
}else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float temp1 = middleBarLayoutParams.weight;
float temp2 = rightBarLayoutParams.weight;
rightBarLayoutParams.weight -= (event.getX()/width);
middleBarLayoutParams.weight = 1 - (rightBarLayoutParams.weight + leftBarLayoutParams.weight);
int tempMinVal = Integer.parseInt(((TextView)findViewById(R.id.tv_range_min)).getText()+"");
int tempMaxVal = (int)(diff*(1 - rightBarLayoutParams.weight) + minVal);
if(tempMaxVal < tempMinVal){
tempMaxVal = tempMinVal;
}
if(tempMaxVal > maxVal){
tempMaxVal = maxVal;
}
((TextView)findViewById(R.id.tv_range_max)).setText(tempMaxVal+"");
if(middleBarLayoutParams.weight > gap/width && rightBarLayoutParams.weight >= 0){
rightBar.setLayoutParams(rightBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}else{
if(rightBarLayoutParams.weight < 0){
rightBarLayoutParams.weight = 0;
middleBarLayoutParams.weight = 1 - (rightBarLayoutParams.weight + leftBarLayoutParams.weight);
}else {
middleBarLayoutParams.weight = gap/width + (tempMaxVal - tempMinVal)/(1.0f*diff);
rightBarLayoutParams.weight = 1 - (leftBarLayoutParams.weight + middleBarLayoutParams.weight);
}
rightBar.setLayoutParams(rightBarLayoutParams);
middleBar.setLayoutParams(middleBarLayoutParams);
}
return true;
}else if (event.getAction() == MotionEvent.ACTION_UP) {
rightThumbPos = Integer.parseInt(((TextView)findViewById(R.id.tv_range_max)).getText()+"");
return true;
}
else
{
return false;
}
}
});
}
public int getMinVal() {
return minVal;
}
public void setMinVal(int minVal) {
this.minVal = minVal;
}
public int getMaxVal() {
return maxVal;
}
public void setMaxVal(int maxVal) {
this.maxVal = maxVal;
}
public int getLeftThumbPos() {
return leftThumbPos;
}
public void setLeftThumbPos(int leftThumbPos) {
this.leftThumbPos = leftThumbPos;
}
public int getRightThumbPos() {
return rightThumbPos;
}
public void setRightThumbPos(int rightThumbPos) {
this.rightThumbPos = rightThumbPos;
}
}
and range_seekbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/ll_range_seekbar"
android:layout_height="wrap_content">
<View
android:layout_width="0dp"
android:layout_weight="0"
android:id="#+id/left_bar"
android:background="#color/light_grey"
android:layout_height="1dp"/>
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="1"
android:id="#+id/middle_bar"
android:layout_height="wrap_content">
<View
android:layout_width="match_parent"
android:layout_centerVertical="true"
android:id="#+id/middle_view"
android:layout_toRightOf="#+id/left_thumb"
android:layout_toLeftOf="#+id/right_thumb"
android:background="#color/color_select_sky_blue"
android:layout_height="1dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/left_thumb"
android:layout_alignParentLeft="true"
android:src="#drawable/seek_thumb_normal"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/right_thumb"
android:layout_alignParentRight="true"
android:src="#drawable/seek_thumb_normal"/>
</RelativeLayout>
<View
android:layout_width="0dp"
android:layout_weight="0"
android:id="#+id/right_bar"
android:background="#color/light_grey"
android:layout_height="1dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:id="#+id/tv_range_min"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="#+id/tv_range_max"/>
</RelativeLayout>
</LinearLayout>
Use them in the activity as follows.
Test.java
public class Test extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
RangeBar rangeBar = (RangeBar) findViewById(R.id.rangebar);
rangeBar.setMinVal(25);
rangeBar.setMaxVal(50);
rangeBar.create();
}
}.
This is the layout file for the activity.
test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:gravity="center"
android:layout_margin="50dp"
android:layout_height="match_parent">
<com.example.pankajkumar.Utils.RangeBar
android:id="#+id/rangebar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Delay in for loop-android

I'm new to android programming and I have a simple question. I have a random number, nr and I generate this number of ImageViews in the same location. Now, I want to apply an animation to each of these images, but not in the same time.
Let's say I want the first image to start moving at sec 0, then image2 at sec 2 and so on.
I have the images in an array, imb_items[].
for(int j=0; j<nr;j++){
imb_items[j].startAnimation(translateAnim);
????? how can I put here the delay?
}
I'm trying for a long time to do this, but I just can't do it with handlers or threads...I think I don't get the concept.
I would be very thankful if somebody would help me understand and give me a sample code that will work in my specific case.
thank you!
public class MyActivity extends ActionBarActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
Animation anim_translate;
public double valoare, produs, scor = 0;
int printfirst, printsecond;
Handler mHandler = new Handler();
int[] idMultiple = new int[]{6, 5, 3, 4, 2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//Img.setVisibility(View.VISIBLE);
//android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Animation translateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translate);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
int dpHeight = (int)(displaymetrics.heightPixels / displaymetrics.density );
int dpWidth = (int)(displaymetrics.widthPixels / displaymetrics.density );
ImageView imb1=(ImageView)findViewById(R.id.ImageView1 );
Toast.makeText(getApplicationContext(), "Spiridusii lui Mos Craciun pregatesc jucariile pentru copii.",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Ei au observat ca unele jucarii sunt incomplete. Ajuta-i sa comande piesele lipsa!",
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), height+"inaltime"+width,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), dpHeight+"inaltime"+dpWidth,
Toast.LENGTH_LONG).show();
RelativeLayout Layout=(RelativeLayout)findViewById(R.id.rel_banda);
ImageView banda=(ImageView) findViewById(R.id.banda);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.Raspuns_user);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(2);
findViewById(R.id.b0).setOnClickListener(this);
findViewById(R.id.b1).setOnClickListener(this);
findViewById(R.id.b2).setOnClickListener(this);
findViewById(R.id.b3).setOnClickListener(this);
findViewById(R.id.b4).setOnClickListener(this);
findViewById(R.id.b5).setOnClickListener(this);
findViewById(R.id.b6).setOnClickListener(this);
findViewById(R.id.b7).setOnClickListener(this);
findViewById(R.id.b8).setOnClickListener(this);
findViewById(R.id.b9).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
Runnable runnable = new Runnable() {
#Override
public void run() {
{
valoare = Double.parseDouble(String.valueOf(mCalculatorDisplay.getText()));
genereaza_imagini();
check_answer();
}
}
};
mHandler.post(runnable);
//genereaza_imagini dinamic de la una la 9 imagini de un anumit tip
}
//max poate fi 5 sau 9
public void genereaza_imagini() {
final TextView et1, et2;
et1 = (TextView) findViewById(R.id.printfirst);
et2 = (TextView) findViewById(R.id.printsecond);
int nr1 = random(5);
printsecond = random(9);
printfirst = idMultiple[nr1 - 1];
produs = printsecond * printfirst;
et1.setTextSize(13);
et2.setTextSize(13);
et1.setText("nr piese lipsa:" + printfirst);
et2.setText("nr jucarii:" + printsecond);
et1.setVisibility(View.VISIBLE);
et2.setVisibility(View.VISIBLE);
ImageView imb1 = (ImageView) findViewById(R.id.ImageView1);
ImageView imb2 = (ImageView) findViewById(R.id.ImageView2);
ImageView imb3 = (ImageView) findViewById(R.id.ImageView3);
ImageView imb4 = (ImageView) findViewById(R.id.ImageView4);
ImageView imb5 = (ImageView) findViewById(R.id.ImageView5);
ImageView imb6 = (ImageView) findViewById(R.id.ImageView6);
ImageView imb7 = (ImageView) findViewById(R.id.ImageView7);
ImageView imb8 = (ImageView) findViewById(R.id.ImageView8);
ImageView imb9 = (ImageView) findViewById(R.id.ImageView9);
final ImageView[] imb_items = new ImageView[]{imb1, imb2, imb3, imb4, imb5, imb6, imb7, imb8, imb9};
for (int j = 0; j < 9; j++) {
RelativeLayout.LayoutParams lp;
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
int dpHeight = (int) (displaymetrics.heightPixels / displaymetrics.density);
int dpWidth = (int) (displaymetrics.widthPixels / displaymetrics.density);
lp.leftMargin = dpWidth / 2 - dpWidth / 10;
lp.topMargin = dpHeight / 4;
imb_items[j].setLayoutParams(lp);
imb_items[j].getLayoutParams().height = 30;
imb_items[j].getLayoutParams().width = 30;
imb_items[j].setImageResource(0);
imb_items[j].setVisibility(View.GONE);
}
final int i = printsecond; // cate imagini din cele 9
if (nr1 == 1) {
Toast.makeText(getApplicationContext(), "Omizilor le lipsesc 6 picioare.",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj1);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 2) {
Toast.makeText(getApplicationContext(), "Florilor le lipsesc 5 petale. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj2);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 3) {
Toast.makeText(getApplicationContext(), "Papusilor le lipsesc 3 nasturi. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj3);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 4) {
Toast.makeText(getApplicationContext(), "Masinilor le lipsesc 4 roti. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj4);
imb_items[j].setVisibility(View.VISIBLE);
}
}
if (nr1 == 5) {
Toast.makeText(getApplicationContext(), "Robotilor le lipsesc 2 antene. ",
Toast.LENGTH_SHORT).show();
for (int j = 0; j < i; j++) {
imb_items[j].setImageResource(R.drawable.obj5);
imb_items[j].setVisibility(View.VISIBLE);
}
}
final Animation translateAnim = AnimationUtils.loadAnimation(MyActivity.this, R.anim.translate);
Thread thread = new Thread() {
public void run() {
while (true) {
try {
for(int j=0; j<i;j++){
imb_items[j].startAnimation(translateAnim); ???????????????????????????????????????????
Thread.sleep(2000);
}
} catch (InterruptedException e) {
Log.v( "tag", "local Thread error");
}
}
}
};
thread.start();
}
public int random(int max) {
Random r = new Random();
int random = r.nextInt(max) + 1;
return random;
}
public void check_answer() {
Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
valoare = Double.parseDouble(String.valueOf(mCalculatorDisplay.getText()));
verifica();
}
});
}
//functie care afiseaza la onCreate, cand apas pe buton 2: nr1, nr2, raspuns corect nr1*nr2
public void verifica() {
final TextView et1, et2;
et1 = (TextView) findViewById(R.id.printfirst);
et2 = (TextView) findViewById(R.id.printsecond);
TextView Scor = (TextView) findViewById(R.id.Scorul);
if (produs == valoare) {
Toast.makeText(getApplicationContext(), "Raspunsul este corect! :)",
Toast.LENGTH_SHORT).show();
Log.v("Produsul este corect=", String.valueOf(produs));
scor = scor + 50;
Scor.setText("Scor:" + scor);
} else {
Toast.makeText(getApplicationContext(), "Raspunsul este gresit! :(",
Toast.LENGTH_SHORT).show();
Log.v("Produsul nu este corect=", String.valueOf(produs));
scor = scor - 50;
Scor.setText("Scor:" + scor);
}
// ca sa actualizeze automat text view-ul raspuns user la 0.0
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation("C");
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
genereaza_imagini();
}
// mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
userIsInTheMiddleOfTypingANumber = true;
}
} else {
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/banda_bk"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="visible"
tools:context=".MyActivity">
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/rel_banda">
<ImageView
android:id="#+id/banda"
android:visibility="visible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/banda" />
<ImageView
android:id="#+id/ImageView1"
android:layout_marginRight="92dp"
android:layout_marginBottom="52dp"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_toLeftOf="#+id/linearLayout4"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView2"
android:layout_alignLeft="#+id/ImageView1"
android:layout_alignStart="#+id/ImageView1"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView3"
android:layout_marginRight="41dp"
android:layout_toLeftOf="#+id/ImageView2"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView4"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="16dp"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView5"
android:layout_marginTop="25dp"
android:layout_below="#+id/ImageView4"
android:layout_alignLeft="#+id/ImageView4"
android:layout_alignStart="#+id/ImageView4"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView6"
android:layout_alignTop="#+id/ImageView5"
android:layout_alignLeft="#+id/ImageView3"
android:layout_alignStart="#+id/ImageView3"
android:layout_marginTop="14dp"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView7"
android:layout_alignTop="#+id/ImageView6"
android:layout_toRightOf="#+id/ImageView6"
android:layout_marginLeft="22dp"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView8"
android:layout_alignTop="#+id/ImageView7"
android:layout_toRightOf="#+id/ImageView2"
android:visibility="gone"/>
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/ImageView9"
android:layout_alignTop="#+id/ImageView8"
android:layout_toRightOf="#+id/ImageView8"
android:layout_marginLeft="26dp"
android:visibility="gone"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<LinearLayout
android:id="#+id/row1"
android:layout_width="600dp"
android:layout_height="wrap_content"
android:gravity="bottom">
<Button
android:id="#+id/b0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".15"
android:text="#string/b0"
android:textSize="12sp" />
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b1"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b2"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b3"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b4"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b5"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b6"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b7"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".15"
android:text="#string/b8"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/b9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight=".15"
android:text="#string/b9"
android:textSize="12sp"
android:visibility="visible" />
<Button
android:id="#+id/buttonClear"
android:layout_width="33dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="#string/buttonClear"
android:textSize="12sp" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linearLayout4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="33dp">
<TextView
android:id="#+id/printfirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<TextView
android:id="#+id/printsecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0" />
<TextView
android:id="#+id/Raspuns_user"
android:layout_width="100dp"
android:layout_weight=".15"
android:maxLines="1"
android:text="0"
android:textColor="#color/textbody"
android:textSize="15sp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="60dp"
android:layout_height="30dp"
android:textSize="10sp"
android:text="Check" />
<TextView
android:id="#+id/Scorul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/textbody"
android:textSize="10sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Ajutati spiridusii sa afle numarul total de piese lipsa. "
android:id="#+id/textView"
android:textSize="13dp"
android:textColor="#color/textbody"
android:layout_alignParentTop="true" />
</RelativeLayout>
Try this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// YOUR CODE HERE
}
}, 2000);
Where 2000 is 2 seconds delay/sleep in main thread.
You can use thread concept and in loop you can use sleep function for delay and you can write your code in it
thread = new Thread() {
public void run() {
while (true) {
try {
YOUR FOR LOOP CODE HERE with this line "Thread.sleep(2000);"
} catch (InterruptedException e) {
Log.e(TAG, "local Thread error", e);
}
}
}
};
thread.start();
For create delay, you can use this code:
try {
Thread.sleep(m); // m is millisecond, if m = 1000 ms then delay = 1 s
}
catch (InterruptedException e) {
e.printStackTrace();
}
If I use this
for(int j=0; j<i;j++) {
final int finalJ = j;
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
imb_items[finalJ].startAnimation(translateAnim);
Log.i("tag", "This'll run 5000 milliseconds later");
}
},
5000 * j
);
}
the problem is that when when the second image starts moving, the first one stops and disappears. I would like all the images to continue their movement.
This is the final solution:
for(int j=0; j<i;j++) {
translateAnim[j].setStartOffset(5000*j);
imb_items[j].startAnimation(translateAnim[j]);
}

how set padding for my imageview?

I created glow effect imageview application. its working fine, my problem is glow effect left,right,bottom,top was little bit hiding so i am trying to set padding but still i have same problem. how to solve this problem?
code:
ImageView mImageBk = (ImageView)itemTemplate.findViewById(R.id.imgBk);
RelativeLayout.LayoutParams ImgBKLayoutParams = new RelativeLayout.LayoutParams(scrWidth/8 + scrWidth/20, scrWidth/8 + scrWidth/20 );
ImgBKLayoutParams.leftMargin =0;
ImgBKLayoutParams.topMargin = 0;
mImageBk.setLayoutParams(ImgBKLayoutParams);
mImageBk.setImageResource(R.drawable.glow_effect);
mImageBk.setPadding(10, 10, 10, 10);
mImageBk.setVisibility(View.GONE);
full code :
public class tttAdapter extends BaseAdapter{
private Context mContext;
private int scrWidth=0;
private int scrHeight=0;
private int scrDpi = 0;
private boolean setInvisible = false;
private boolean visibleConf[];
private boolean selected[];
private boolean innerListView = false;
private int[] IMAGE_IDS = {
R.drawable.s_record, R.drawable.s_record
};
private String[] title = {
"Tv", "My Favorites List1"
};
private String[] detail = {
"Tv", "My Favorites List1"
};
public favoritesAdapter(Context context) {
mContext = context;
visibleConf = new boolean[IMAGE_IDS.length];
selected = new boolean[IMAGE_IDS.length];
}
public void updateImageSize(int width, int height, int dpi) {
scrWidth= width;
scrHeight = height;
scrDpi = dpi;
}
public void setTextVisible(int position){
if(IMAGE_IDS.length <= position)
return;
for(int i=0; i < IMAGE_IDS.length; i++) {
visibleConf[i] = false;
}
visibleConf[position] = true;
}
public int getCount() {
return IMAGE_IDS.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setTextInvisible(int position) {
visibleConf[position] = false;
}
public void setInnerViewVisible(boolean enable) {
innerListView = enable;
}
public void unsetSelectedItem(int position) {
for(int i=0; i < IMAGE_IDS.length; i++) {
selected[i] = false;
}
}
public void setSelectedItem(int position) {
for(int i=0; i < IMAGE_IDS.length; i++) {
selected[i] = false;
}
selected[position] = true;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemTemplate = inflater.inflate(R.layout.list_item, null);
ImageView mImageBk = (ImageView)itemTemplate.findViewById(R.id.imgBk);
RelativeLayout.LayoutParams ImgBKLayoutParams = new RelativeLayout.LayoutParams(scrWidth/8 + scrWidth/20, scrWidth/8 + scrWidth/20 );
ImgBKLayoutParams.leftMargin =0;
ImgBKLayoutParams.topMargin = 0;
mImageBk.setLayoutParams(ImgBKLayoutParams);
mImageBk.setImageResource(R.drawable.glow_effect);
mImageBk.setPadding(10, 10, 10, 10);
mImageBk.setVisibility(View.GONE);
ImageView mImage = (ImageView)itemTemplate.findViewById(R.id.img);
RelativeLayout.LayoutParams ImgLayoutParams = new RelativeLayout.LayoutParams(scrWidth/8 , scrWidth/8 );
ImgLayoutParams.leftMargin = scrWidth/38;
ImgLayoutParams.topMargin = scrWidth/38;
mImage.setLayoutParams(ImgLayoutParams);
mImage.setImageResource(IMAGE_IDS[position]);
mImage.bringToFront();
TextView mTextTitle = (TextView)itemTemplate.findViewById(R.id.title);
mTextTitle.setClickable(false);
mTextTitle.setEnabled(true);
mTextTitle.setText(title[position]);
TextView mTextDetail = (TextView)itemTemplate.findViewById(R.id.detail);
mTextDetail.setClickable(false);
mTextDetail.setEnabled(true);
mTextDetail.setText(detail[position]);
if(selected[position] == true) {
ImageView mArrowImg = (ImageView)itemTemplate.findViewById(R.id.imgArrow);
//mArrowImg.setLayoutParams(new RelativeLayout.LayoutParams(scrWidth/32, scrHeight/32));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(scrWidth/32, scrHeight/32);
layoutParams.leftMargin = scrWidth / 8;
layoutParams.topMargin = scrWidth / 16;
mArrowImg.setLayoutParams(layoutParams);
mArrowImg.setImageResource(R.drawable.arrow);
mImage.setBackgroundResource(R.drawable.test_glowb);
mTextTitle.setVisibility(View.GONE);
mTextDetail.setVisibility(View.GONE);
mImageBk.setVisibility(View.VISIBLE);
} else {
if(innerListView == true) {
mImage.setVisibility(View.GONE);
}
}
if(visibleConf[position] == true) {
mTextTitle.setTextSize((scrWidth*160) / (30 * scrDpi));
mTextDetail.setTextSize((scrWidth*160) / (50 * scrDpi));
mTextTitle.setTypeface(null,Typeface.BOLD);
mTextDetail.setTypeface(null,Typeface.BOLD);
mImageBk.setVisibility(View.VISIBLE);
} else {
mTextTitle.setTextSize((scrWidth*160) / (40 * scrDpi));
mTextDetail.setTextSize((scrWidth*160) / (70 * scrDpi));
//mTextTitle.setVisibility(View.GONE);
//mTextDetail.setVisibility(View.GONE);
mImage.setAlpha(150);
}
if(innerListView == true) {
mTextTitle.setVisibility(View.GONE);
mTextDetail.setVisibility(View.GONE);
}
return itemTemplate;
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imgBk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="14dip"
android:layout_marginTop="30dp"
android:layout_centerInParent="true"
android:layout_toRightOf="#+id/thumb"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumb"
android:layout_toRightOf="#+id/thumb"
android:layout_centerVertical="true"
android:textColor="#ffffff" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/thumb"
android:layout_alignParentBottom="true"
android:textColor="#ffffff" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgArrow"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
</LinearLayout>
</RelativeLayout>
Be sure that you are setting margins/padding for the imageview widget as opposed to the layout container.
i think you want margins and not padding (for the imageView) , since padding puts spaces in the content of the view , meaning less space to show anything.
margins are outside of the view.

Categories

Resources