How to run timer one after another in android? - java

How to run timer one after another?
for eg: I am using two edittext and one button,
after giving input to 2 edittext as 1 and 2(in minutes), the timer should first complete the first given input and then to start the 2nd input.
Then when i click stop timer, it should stop and display the edittext input and the stopped timer value.
but it's working only for 1st input..but fails in second input.
Here is the code which I tried.
public class MainActivity extends Activity implements OnClickListener {
private Button buttonStartTime, buttonStopTime;
private EditText edtTimerValue;
private EditText edtTimerValue1;
private TextView textViewShowTime; // will show the time
private TextView textViewShowTime1; // will show the time
private CountDownTimer countDownTimer; // built in android class
private CountDownTimer countDownTimer1; // built in android class
// CountDownTimer
private long totalTimeCountInMilliseconds; // total count down time in
private long totalTimeCountInMilliseconds1;
// milliseconds
private long timeBlinkInMilliseconds; // start time of start blinking
private long timeBlinkInMilliseconds1;
private boolean blink; // controls the blinking .. on and off
private boolean blink1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
buttonStopTime = (Button) findViewById(R.id.btnStopTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
edtTimerValue = (EditText) findViewById(R.id.edtTimerValue);
buttonStartTime.setOnClickListener(this);
buttonStopTime.setOnClickListener(this);
textViewShowTime1 = (TextView) findViewById(R.id.tvTimeCount1);
edtTimerValue1 = (EditText) findViewById(R.id.edtTimerValue2);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnStartTime) {
textViewShowTime.setTextSize(15);
setTimer();
buttonStopTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.GONE);
edtTimerValue.setText("");
startTimer();
} else if (v.getId() == R.id.btnStopTime) {
countDownTimer.cancel();
if(countDownTimer1!=null) {
countDownTimer1.cancel();
}
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
}
}
private void setTimer() {
int time = 0;
if (!edtTimerValue.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue.getText().toString());
} else
Toast.makeText(MainActivity.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds = 60 * time * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
if (blink) {
textViewShowTime.setVisibility(View.VISIBLE);
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink; // toggle the value of blink
}
textViewShowTime.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
setTimer1(); //here i am using two call the second input
startTimer1(); //here i am using to start the second input automatically.
}
}.start();
}
//this is not working..
private void setTimer1() {
Log.e("text","tesxt");
int time = 0;
if (!edtTimerValue1.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue1.getText().toString());
} else
Toast.makeText(MainActivity.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds1 = 60 * time * 1000;
timeBlinkInMilliseconds1 = 30 * 1000;
}
//this function is also not working to start the second input..
private void startTimer1() {
Log.e("time","time");
countDownTimer1 = new CountDownTimer(timeBlinkInMilliseconds1, 500) {
#Override
public void onTick(long millisUntilFinished) {
long seconds = millisUntilFinished / 1000;
if (millisUntilFinished < timeBlinkInMilliseconds) {
if (blink1) {
textViewShowTime1.setVisibility(View.VISIBLE);
} else {
textViewShowTime1.setVisibility(View.INVISIBLE);
}
blink1 = !blink1;
}
textViewShowTime1.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
textViewShowTime1.setText("Time up!");
textViewShowTime1.setVisibility(View.VISIBLE);
edtTimerValue1.setVisibility(View.VISIBLE);
}
}.start();
}
}
The layout is this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<EditText
android:id="#+id/edtTimerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="minutes"
android:inputType="phone" />
<Button
android:id="#+id/btnStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Start Timer" />
<Button
android:id="#+id/btnStopTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Stop Timer"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTimeCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textStyle="bold"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<EditText
android:id="#+id/edtTimerValue2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="minutes"
android:inputType="phone" />
<Button
android:id="#+id/btnStartTime2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Start Timer"
android:visibility="gone"/>
<Button
android:id="#+id/btnStopTime2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Stop Timer"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTimeCount1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>

Related

Combine use of OnClickListener and OnLong Click Listener

Actually I created a pdf viewer and i jus want to create a longclicklistener to open my new activity and as u can see here
Screenshot
And there is already a click listener assigned with this button and i also want to combine longclicklistener so when i long click that button then automatically launch my second activity
public void actionButtonClick(View view) {
if (pageCount == 0) {
Toast.makeText(getApplicationContext(), getString(R.string.no_selected_pdf), Toast.LENGTH_LONG).show();
return;
}
final BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
dialog.setContentView(R.layout.bottom_sheet);
dialog.setCanceledOnTouchOutside(true);
NumberPicker numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
if (numberPicker != null) {
numberPicker.setMaxValue(pageCount);
numberPicker.setValue(pdfView.getCurrentPage() + 1);
numberPicker.setOnValueChangedListener((picker, oldVal, newVal) -> {
pdfView.jumpTo(newVal - 1, true);
});
}
dialog.show();
}
public void openButtonClick(View view) {
launchPicker();
}
private void startAnimation(int state) {
actionLayout.animate()
.translationY(state == 0 ? actionLayout.getHeight() : 0)
.alpha(state == 0 ? 0 : 1.0f)
.setDuration(300).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
menu.findItem(R.id.hide_or_show_button).setChecked(state != 1);
super.onAnimationEnd(animation);
}
});
}
private void hideOrShowActionButton() {
if (actionLayout.getAlpha() == 1.0)
startAnimation(0);
else
startAnimation(1);
}
private void showSnackBar(#NonNull String msg, boolean isError) {
Snackbar snackbar = Snackbar
.make(findViewById(R.id.main_layout), msg, Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()),
isError ? R.color.err_color : R.color.main_color));
snackbar.setTextColor(ContextCompat
.getColor(Objects.requireNonNull(getApplicationContext()), R.color.white));
snackbar.show();
}
#Override
public void loadComplete(int nbPages) {
pageCount = nbPages;
warningLayout.setVisibility(View.GONE);
PdfDocument.Meta meta = pdfView.getDocumentMeta();
detailsMap.clear();
detailsMap.add(meta.getTitle());
detailsMap.add(meta.getAuthor());
detailsMap.add(meta.getSubject());
detailsMap.add(meta.getKeywords());
detailsMap.add(meta.getCreator());
detailsMap.add(meta.getProducer());
detailsMap.add(dateFormatter(meta.getCreationDate()));
detailsMap.add(dateFormatter(meta.getModDate()));
}
private String dateFormatter(String data) {
if (!data.isEmpty()) {
String date = data.substring(2);
String y = date.substring(0, 4);
String m = date.substring(4, 6);
String d = date.substring(6, 8);
return y + "/" + m + "/" + d;
} else {
return data;
}
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber.setText(String.valueOf(page + 1));
}
#Override
public void onPageError(int page, Throwable t) {
showSnackBar(getString(R.string.page_not_loaded) + page, true);
}
}
Xml File
This Is Xml File if needed
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdf_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
app:layout_anchor="#+id/warning"
app:layout_anchorGravity="center">
<Button
android:id="#+id/button"
android:layout_width="42dp"
android:layout_height="11dp"
android:layout_below="#id/textView"
android:layout_alignParentBottom="true"
android:layout_marginBottom="518dp"
android:text="open activity 2" />
</com.github.barteksc.pdfviewer.PDFView>
<LinearLayout
android:id="#+id/warning"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/no_selected_pdf"
android:textColor="#color/secondary_text_color"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_open_pdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"
android:focusable="true"
android:onClick="openButtonClick"
android:padding="10dp"
android:text="#string/click_to_select_pdf"
android:textColor="#color/main_color"
android:textSize="18sp" />
</LinearLayout>
<FrameLayout
android:id="#+id/action_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:contentDescription="#string/action_btn_description"
android:onClick="actionButtonClick"
app:backgroundTint="#color/main_color"
app:borderWidth="0dp"
app:tint="#color/white" />
<TextView
android:id="#+id/tv_page_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:elevation="16dp"
android:text="x"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/white"
android:textSize="16sp" />
</FrameLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
There is an onClick and onLongClick listener for each view :
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
FloatingActionButton actionButton = findViewById(R.id.actionButton);
actionButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// start your activity from here
return true;
}
});
}

Transition from Button to EditText

I want to have a transition in my android views on view is Button and other is EditText, transitions must be like this animation
I tried in this way
Layout xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.itc.org.todo.MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="#android:color/white"
android:gravity="center_horizontal|center_vertical">
<TextView
android:id="#+id/title_tv"
android:text="#string/to_do"
android:textSize="22sp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"/>
<TextView
android:id="#+id/date_tv"
android:textSize="16sp"
android:textColor="#android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/colorGray"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:text="#string/what_do_you_want_to_do_today"
android:textSize="16sp"
android:textColor="#android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"/>
<TextView
android:text="#string/start_adding_items_to_your_to_do_list"
android:textSize="16sp"
android:textColor="#android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/transitions_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible">
<Button
android:id="#+id/add_btn"
android:layout_width="200dp"
android:layout_height="60dp"
android:text="#string/add_item"
android:textSize="18sp"
android:paddingLeft="20dp"
android:textColor="#android:color/white"
android:drawableLeft="#drawable/ic_add_24dp"
android:background="#drawable/rounded_black_bg"
android:layout_gravity="center"/>
<EditText
android:id="#+id/item_input_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:minHeight="50dp"
android:layout_marginLeft="#dimen/margin_30dp"
android:layout_marginRight="#dimen/margin_30dp"
android:paddingLeft="#dimen/dimen_20dp"
android:paddingRight="#dimen/dimen_50dp"
android:textColor="#android:color/black"
android:inputType="text"
android:background="#drawable/rounded_edit_text"
android:layout_gravity="center"/>
</FrameLayout>
</RelativeLayout>
Preview is
Java code is
public class MainActivity extends AppCompatActivity {
private EditText mItemInputEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView dateTextView = (TextView) findViewById(R.id.date_tv);
mItemInputEditText = (EditText) findViewById(R.id.item_input_et);
final Button addButton = (Button) findViewById(R.id.add_btn);
final ViewGroup transitionsContainer = (ViewGroup) findViewById(R.id.transitions_container);
mItemInputEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
TransitionSet set = new TransitionSet()
.addTransition(new Fade())
.setInterpolator(new FastOutLinearInInterpolator());
TransitionManager.beginDelayedTransition(transitionsContainer, set);
}
addButton.setVisibility(View.VISIBLE);
mItemInputEditText.setVisibility(View.GONE);
}
});
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
TransitionSet set = new TransitionSet()
.addTransition(new Fade())
.setInterpolator(new FastOutLinearInInterpolator());
TransitionManager.beginDelayedTransition(transitionsContainer, set);
}
addButton.setVisibility(View.GONE);
mItemInputEditText.setVisibility(View.VISIBLE);
}
});
SimpleDateFormat dt = new SimpleDateFormat("EEE d MMM yyyy");
dateTextView.setText(dt.format(new Date()));
}
}
but with this code the resulting transition is
As you can see this is bit weird as compared to expected one, can any one suggest me some changes to get the desired transitions.
Transitions API is surely nice thing, but it cannot solve each and everything for you. You haven't instructed how to perform that animation to the transition framework, how come it would understand what is the final animation that you want to perform?
I'm not sure this animation can be achieved using solely Transitions API. Instead, you can stick to standard animations APIs, e.g. ValueAnimator.
The animation consists of several stages. When a button is clicked, you want it to become slightly wider, also losing its transparency. And after this is done, you want the EditText to come into the scene and be animated to its final value starting from the width, where the button was landed at.
So, inside button click listener:
#Override
public void onClick(View v) {
final int from = addButton.getWidth();
final int to = (int) (from * 1.2f); // increase by 20%
final LinearInterpolator interpolator = new LinearInterpolator();
ValueAnimator firstAnimator = ValueAnimator.ofInt(from, to);
firstAnimator.setTarget(addButton);
firstAnimator.setInterpolator(interpolator);
firstAnimator.setDuration(DURATION);
final ViewGroup.LayoutParams params = addButton.getLayoutParams();
firstAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
params.width = (Integer) animation.getAnimatedValue();
addButton.setAlpha(1 - animation.getAnimatedFraction());
addButton.requestLayout();
}
});
firstAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
// reset alpha channel
addButton.setAlpha(1.0f);
addButton.setVisibility(View.GONE);
mItemInputEditText.setVisibility(View.VISIBLE);
ValueAnimator secondAnimator = ValueAnimator.ofInt(to, editTextWidth);
secondAnimator.setTarget(mItemInputEditText);
secondAnimator.setInterpolator(interpolator);
secondAnimator.setDuration(DURATION);
final ViewGroup.LayoutParams params = mItemInputEditText.getLayoutParams();
secondAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
params.width = (Integer) animation.getAnimatedValue();
mItemInputEditText.requestLayout();
}
});
secondAnimator.start();
}
});
firstAnimator.start();
}
Similar actions are performed when coming back from EditText to button:
#Override
public void onClick(View view) {
final int from = mItemInputEditText.getWidth();
final int to = (int) (from * 0.8f);
final LinearInterpolator interpolator = new LinearInterpolator();
ValueAnimator firstAnimator = ValueAnimator.ofInt(from, to);
firstAnimator.setTarget(mItemInputEditText);
firstAnimator.setInterpolator(interpolator);
firstAnimator.setDuration(DURATION);
final ViewGroup.LayoutParams params = mItemInputEditText.getLayoutParams();
firstAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
params.width = (Integer) animation.getAnimatedValue();
mItemInputEditText.requestLayout();
}
});
firstAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mItemInputEditText.setVisibility(View.GONE);
addButton.setVisibility(View.VISIBLE);
ValueAnimator secondAnimator = ValueAnimator.ofInt(to, buttonWidth);
secondAnimator.setTarget(addButton);
secondAnimator.setInterpolator(interpolator);
secondAnimator.setDuration(DURATION);
final ViewGroup.LayoutParams params = addButton.getLayoutParams();
secondAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
params.width = (Integer) animation.getAnimatedValue();
addButton.setAlpha(animation.getAnimatedFraction());
addButton.requestLayout();
}
});
secondAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
addButton.setAlpha(0.0f);
}
});
secondAnimator.start();
}
});
firstAnimator.start();
}
editTextWidth and buttonWidth are initial sizes of views:
private int editTextWidth, buttonWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
// `transitions_container` is the parent of both `EditText` and `Button`
// Thus, posting on it ensures that both of those views are laid out when this runnable is executed
findViewById(R.id.transitions_container).post(new Runnable() {
#Override
public void run() {
editTextWidth = mItemInputEditText.getWidth();
// `mItemInputEditText` should be left visible from XML in order to get measured
// setting to GONE after we have got actual width
mItemInputEditText.setVisibility(View.GONE);
buttonWidth = addButton.getWidth();
}
});
}
Here's the output:
You can have the patch file with changes here.
First, change your Layout XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.itc.org.todo.MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="#android:color/white"
android:gravity="center_horizontal|center_vertical">
<TextView
android:id="#+id/title_tv"
android:text="#string/to_do"
android:textSize="22sp"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"/>
<TextView
android:id="#+id/date_tv"
android:textSize="16sp"
android:textColor="#android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/colorGray"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<TextView
android:text="#string/what_do_you_want_to_do_today"
android:textSize="16sp"
android:textColor="#android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"/>
<TextView
android:text="#string/start_adding_items_to_your_to_do_list"
android:textSize="16sp"
android:textColor="#android:color/darker_gray"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/transitions_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible">
<include layout="#layout/a_scene" />
</FrameLayout>
</RelativeLayout>
Then create your first scene for the button.
The layout for the first scene is defined as follows:
res/layout/a_scene.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scene_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/add_btn"
android:layout_width="200dp"
android:layout_height="60dp"
android:text="#string/add_item"
android:textSize="18sp"
android:paddingLeft="20dp"
android:textColor="#android:color/white"
android:drawableLeft="#drawable/ic_add_24dp"
android:background="#drawable/rounded_black_bg"
android:layout_gravity="center"/>
</RelativeLayout>
The layout for the second scene contains editText (with the same IDs) and is defined as follows:
res/layout/another_scene.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scene_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/add_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:minHeight="50dp"
android:layout_marginLeft="#dimen/margin_30dp"
android:layout_marginRight="#dimen/margin_30dp"
android:paddingLeft="#dimen/dimen_20dp"
android:paddingRight="#dimen/dimen_50dp"
android:textColor="#android:color/black"
android:inputType="text"
android:background="#drawable/rounded_edit_text"
android:layout_gravity="center"/>
</RelativeLayout>
Java Code:
public class MainActivity extends AppCompatActivity {
private EditText mItemInputEditText;
private Scene mAScene;
private Scene mAnotherScene;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView dateTextView = (TextView) findViewById(R.id.date_tv);
mItemInputEditText = (EditText) findViewById(R.id.item_input_et);
final Button addButton = (Button) findViewById(R.id.add_btn);
final ViewGroup transitionsContainer = (ViewGroup) findViewById(R.id.transitions_container);
// Create the scenes
mAScene = Scene.getSceneForLayout(mSceneRoot, R.layout.a_scene, this);
mAnotherScene = Scene.getSceneForLayout(mSceneRoot, R.layout.another_scene, this);
mItemInputEditText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Transition transition = new ChangeBounds();
TransitionManager.go(mAScene, transition);
}
addButton.setVisibility(View.VISIBLE);
mItemInputEditText.setVisibility(View.GONE);
}
});
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Transition transition = new ChangeBounds();
TransitionManager.go(mAnotherScenetransition);
}
addButton.setVisibility(View.GONE);
mItemInputEditText.setVisibility(View.VISIBLE);
}
});
SimpleDateFormat dt = new SimpleDateFormat("EEE d MMM yyyy");
dateTextView.setText(dt.format(new Date()));
}
}
You can use FABReveal Layout for that. Take a reference from that and change Relative layout to button. and modify it as per requirement.
XML
<com.truizlop.fabreveallayout.FABRevealLayout
android:id="#+id/fab_reveal_layout"
android:layout_width="match_parent"
android:layout_height="#dimen/fab_reveal_height"
>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="#color/some_color"
android:src="#drawable/some_drawable"
/>
<RelativeLayout
android:id="#+id/main_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</RelativeLayout>
<RelativeLayout
android:id="#+id/secondary_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</RelativeLayout>
</com.truizlop.fabreveallayout.FABRevealLayout>
https://github.com/truizlop/FABRevealLayout
https://github.com/saulmm/Curved-Fab-Reveal-Example

countdown with editText

I would like to create a countdown where the initial number is given by the user. I created this application but when the application starts shut down. I do not understand what the mistake is because there are no errors during the compilation. What am I doing wrong?
this is the code:
public class Main2Activity extends AppCompatActivity {
Button bstart, bStopReset;
EditText editTimer;
CountDownTimer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editTimer = (EditText) findViewById(R.id.contatore);
bstart = (Button) findViewById(R.id.start);
bStopReset = (Button) findViewById(R.id.stop_reset);
}
String valore = editTimer.getText().toString();
int ValoreIntero = Integer.parseInt(valore);
public void startOnClick(View view) {
timer = new CountDownTimer(ValoreIntero, 1000) {
#Override
public void onTick(final long millSecondsLeftToFinish) {
String time = String.valueOf(millSecondsLeftToFinish / 1000);
editTimer.setText(time);
}
#Override
public void onFinish() {
editTimer.setText("Done!");
}
};
timer.start();
}
public void stopOnClick(View view) {
timer.cancel();
editTimer.setText("0");
}
}
xml:
<?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:id="#+id/activity_main2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_bright"
android:orientation="vertical"
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:weightSum="1"
tools:context="com.example.gabrypacor.orologio.Main2Activity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.39"
android:gravity="center"
android:text="countdown"
android:textAlignment="center"
android:textSize="36sp" />
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.27"
android:gravity="center"
android:text="inserisci il tempo del countdown nel riquadro blu"
android:textAlignment="center"
android:textSize="20sp"
tools:textAlignment="center" />
<EditText
android:id="#+id/contatore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.21"
android:background="#android:color/holo_blue_light"
android:ems="10"
android:inputType="numberDecimal"
android:text="0"
android:textAlignment="center"
android:textColorLink="?android:attr/textColorPrimaryDisableOnly"
android:textSize="60sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.18"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_weight="1"
android:onClick="startOnClick"
android:text="inizio" />
<Button
android:id="#+id/stop_reset"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_weight="1"
android:onClick="stopOnClick"
android:text="stop/reset" />
</LinearLayout>
You are setting these two values when your activity is initialized rather than when the user clicks the start button:
String valore = editTimer.getText().toString();
int ValoreIntero = Integer.parseInt(valore);
Move them into your startOnClick method and that should fix the exception you are getting.

How to make a countdown timer repeat

It is my first time working with Android Studio and my Java skills are basically non-existent so I need a little help with a project I am working on.
I need to make a timer that repeats after a certain break. The user should decide how many times should timer repeat and what is the duration of break.
So far I did the standard countdown timer but no matter what i try i can't make it repeat
That is the working code I have so far
Interface:
<LinearLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.asus.timer.MainActivity"
android:padding="20dp"
android:orientation="vertical"
>
<EditText
android:id="#+id/editTextSession"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:padding="20dp"
android:hint="Session (seconds)"
android:textAlignment="center"
/>
<EditText
android:id="#+id/editTextBreak"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:padding="20dp"
android:hint="Break (seconds)"
android:textAlignment="center"
/>
<EditText
android:id="#+id/editTextRepeats"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:padding="20dp"
android:hint="Repeats"
android:textAlignment="center"
/>
<Button
android:id="#+id/buttonStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start!"
android:padding="20dp"
/>
<TextView
android:id="#+id/textViewTimer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:padding="20dp"
android:textAlignment="center"
android:textSize="60dp"
android:paddingTop="40dp"
android:gravity="center"
/>
Functionality
public class MainActivity extends AppCompatActivity {
EditText editTextSession;
EditText editTextBreak;
EditText editTextRepeats;
Button buttonStart;
TextView textViewTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextSession =(EditText) findViewById(R.id.editTextSession);
editTextBreak =(EditText) findViewById(R.id.editTextBreak);
editTextRepeats =(EditText) findViewById(R.id.editTextRepeats);
buttonStart =(Button) findViewById(R.id.buttonStart);
textViewTimer =(TextView) findViewById(R.id.textViewTimer);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editTextSession.getText().toString();
int seconds = Integer.valueOf(editTextSession.getText().toString());
CountDownTimer countDownTimer = new CountDownTimer(seconds * 1000, 1000) {
#Override
public void onTick(long millis) {
textViewTimer.setText("time:" + (int) (millis / 1000));
}
#Override
public void onFinish() {
extViewTimer.setText("Finished!");
}
}.start();
}
}
);
Did You try Integer.parseInt(String value) instead of Integer.valueOf(String value)? Maybe it will make a diffrence. You can add an exception if someone type wrong value.
if you're looking for another way to create timer, you can do something like this with Runnable() :
private TextView timeCounterTextView;
private int smsTimeOut = 10; // 10 SECONDS
private Runnable timeCounterRunnable = new Runnable() {
#Override
public void run() {
if (smsTimeOut == 1) {
//Do whatever when timeout
}
smsTimeOut--;
timeCounterTextView.setText(String.valueOf(smsTimeOut));
handler.postDelayed(this, 1000);
}
};
and whenever you want to start countdown initialize and start timer with init() method like below :
private void init(){
handler.removeCallbacks(timeCounterRunnable);
smsTimeOut = 10;
handler = new Handler();
handler.post(timeCounterRunnable);
}
anytime you want to repeat you can call init() again.
hope this helps.
Use this
timer.start();
And stop it with:
timer.cancel();
Example:
String text = editTextSession.getText().toString();
int seconds = Integer.valueOf(text);
//get how many repeat
String repeatText = editTextSession.getText().toString();
int repeat = Integer.valueOf(repeatText);
int count= 0;
CountDownTimer countDownTimer = new CountDownTimer(seconds * 1000, 1000) {
#Override
public void onTick(long millis) {
textViewTimer.setText("time:" + (int)(millis / 1000));
}
#Override
public void onFinish() {
extViewTimer.setText("Finished!");
count++;
//check if count still less than repeat number
if(count < repeat){
Runnable r = new Runnable() {
public void run() {
countDownTimer.start();
}};
new Handler().postDelayed(r,2000); //delay repeat timer 2 seconds
}
else{
countDownTimer.cancel();
count = 0;
}
}
}.start();

handling too many requests of animation on the main ui thread from other threads - android

I am working on creating activity that has too many animations, and when starting this activity the logcat shows me this message again and again during the life time of this activity:
I/Choreographer﹕ Skipped 36 frames! The application may be doing too much work on its main thread.
so I did many stuff in another threads, but still there is heavy access on the main UI thread. as well as, the animation is becoming really slow on some high resolution devices
what can be possible solution for handling this problem ?
UPDATED: added code
so here is the code of showing the views(which are 6 imageButtons),
private void setupAnimationForAllViews(ArrayList<View> listOfViews,
int animationId,
final boolean isAppearing) {
int startDelay = mDelay; // milliseconds
int numberOfViews = listOfViews.size();
for (int i = 0; i < numberOfViews; i++) {
final Animation animator = AnimationUtils.loadAnimation(mContext, animationId);
animator.setStartOffset(startDelay);
startDelay += mOffSet; // every view will start after 100 milliseconds from the other
final View currentView = listOfViews.get(i);
final int indexOfCurrentCheckedItem = i;
mMainUIThreadHandler.post(new Runnable() {
#Override
public void run() {
currentView.startAnimation(animator);
}
});
}
}
I trigger it in seperated thread like this:
new Thread(new Runnable() {
#Override
public void run() {
setupAnimationForAllViews(tempListOfViews,
animationId, isAppearing);
}
}).start();
In the same activity i have Ken Burns View, which implement ken burns effect on 2 images, The code of this kenBurnsView is in this link: KenBurnsView
so this is the main activity xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#111"
android:orientation="vertical"
android:weightSum="7">
<FrameLayout
android:id="#+id/header"
android:layout_weight="6"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<yasinseyhan.com.yukselirgroup.Activities.GeneralActivities.KenBurnsView
android:id="#+id/header_picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/uphill2" />
<ImageView
android:id="#+id/header_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/header_white" />
</FrameLayout>
<LinearLayout
android:id="#+id/dsd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
android:weightSum="3"
android:orientation="vertical"
>
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#android:color/white"
android:layout_weight="0.5"/>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/btnKur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_kurumsal_selector"/>
<ImageView
android:id="#+id/btnGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_groups"/>
<ImageView
android:id="#+id/btnSektorelFaa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_sektorel_selector"/>
</LinearLayout>
<LinearLayout
android:id="#+id/secondLineLinearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="#+id/btnInsanKayna"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_ik_selector"/>
<ImageView
android:id="#+id/btnGale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_galeri_selector"/>
<ImageView
android:id="#+id/btnIlet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/btn_iletisim_selector"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_weight="0.5"
android:background="#android:color/white"/>
</LinearLayout>
</LinearLayout>
This is the main activity java part:
public class MainActivity extends Activity {
//Buttons in the MainActivity
AnimationHelper animationHelper;
ArrayList<View> listOfButtons;
Handler mUIThreadHandler = new Handler();
private final int hideOnClickAnimation = R.anim.fade_out;
private final int displayAnimation = R.anim.test_anim;
//For Kenburns View with multible images
private KenBurnsView mKenBurnsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initAnimation();
init();
// for testing, we may put those in initAnimation()
animationHelper.setDelay(100);
animationHelper.setOffSet(50);
mKenBurnsView.setResourceIds(R.drawable.test16, R.drawable.uphill2);
}
private void initAnimation() {
//Adding OnClickListeners to the Buttons in the MainActivity - End
// The order is important here
listOfButtons = new ArrayList<>();
listOfButtons.add(btnGroupSirketleri);
listOfButtons.add(btnGale);
listOfButtons.add(btnSektorelFaa);
listOfButtons.add(btnKur);
listOfButtons.add(btnInsanKayna);
listOfButtons.add(btnIlet);
// Adding Animation
animationHelper = new AnimationHelper(listOfButtons, this, mUIThreadHandler);
}
private void initUI() {
//initializing the buttons in the mainactivity
btnKur = (ImageView) findViewById(R.id.btnKur);
btnGroup = (ImageView) findViewById(R.id.btnGroup);
btnSektorelFaa = (ImageView) findViewById(R.id.btnSektorelFaa);
btnInsanKayna = (ImageView) findViewById(R.id.btnInsanKayna);
btnGale = (ImageView) findViewById(R.id.btnGale);
btnIlet = (ImageView) findViewById(R.id.btnIlet);
// KenBurns View
mKenBurnsView = (KenBurnsView) findViewById(R.id.header_picture);
}
private void init() {
//Adding OnClickListeners to the Buttons in the MainActivity - Start
btnKur.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnSektorelFaa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnInsanKayna.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnGale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
btnIlet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animationHelper.hideViewsWithClickedView(hideOnClickAnimation, v);
}
});
}
#Override
protected void onResume() {
super.onResume();
animationHelper.displayViews(displayAnimation, new IDoOnEndOfWholeAnimation() {
#Override
public void doIt() {
if (!mKenBurnsView.isAnimating)
mKenBurnsView.startKenBurnsAnimation();
}
});
}
#Override
protected void onPause() {
super.onPause();
if (mKenBurnsView.isAnimating)
mKenBurnsView.stopKenBurnsAnimation();
}
}
I reduced the sizes and a little bit the resolution of images for Kenburns and the buttons backgrounds in order to get it working smoothly. Playing with threads did not solve the issue of lagging for me.

Categories

Resources