Here am selecting arrival and exit time using imageview with help of TimePickerFragment, DialogFragment.
My question is how to select the exit time..When am selecting exit time it will show in the arrival time text box only. How to solve this problem help me.
Here code for arrival and exit time
Am using two text box and two image view button.
import java.util.Calendar;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TimePicker;
#SuppressLint("ValidFragment")
public class MainActivity extends FragmentActivity {
EditText arrtime,exittime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectArrivalTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "TimePicker");
}
public void selectExitTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "TimePicker");
}
public void populateSetArrTime(int hourOfDay, int minute) {
arrtime = (EditText)findViewById(R.id.editText1);
arrtime.setText(+hourOfDay+":"+minute);
}
public void populateSetExitTime(int hourOfDay, int minute) {
exittime= (EditText)findViewById(R.id.editText2);
exittime.setText(+hourOfDay+":"+minute);
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
populateSetArrTime(hourOfDay, minute);
}
public void onTimeSet1(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
populateSetExitTime(hourOfDay, minute);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my XML layout.
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="67dp"
android:text="Arrival time" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/editText1"
android:layout_marginTop="30dp"
android:text="Exit time" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView1"
android:layout_toRightOf="#+id/textView1"
android:clickable="false"
android:ems="10"
android:focusable="false"
android:focusableInTouchMode="false"
android:inputType="time" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignLeft="#+id/editText1"
android:clickable="false"
android:ems="10"
android:focusable="false"
android:focusableInTouchMode="false"
android:inputType="time" >
</EditText>
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/editText2"
android:layout_marginTop="51dp"
android:contentDescription="#string/selectarrtime"
android:onClick="selectArrivalTime"
android:src="#drawable/ic_launcher" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/editText2"
android:layout_alignTop="#+id/imageButton1"
android:layout_marginRight="33dp"
android:contentDescription="#string/selectexittime"
android:onClick="selectExitTime"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
If select a arrival time i will shows time in my arrival edit text box and also if i select a exit time it will shows the time in same arrival edit text box not displaying in my exit edit text box how to slove this pls help me thanks in advance.
#SuppressLint("ValidFragment")
public class MainActivity extends FragmentActivity {
EditText arrtime,exittime;
static type=""; //changed
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton b1=(ImageButton)findViewById(R.id.imageButton1); //changed from here
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTime("arrival");
}
});
ImageButton b2=(ImageButton)findViewById(R.id.imageButton2);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setTime("exit");
}
}); ///to here
}
public void setTime(String type) { //function changed
MainActivity.type=type;
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "TimePicker");
}
public void populateTime(int hourOfDay, int minute) { //function changed
if(type.equals("arrival") {
arrtime = (EditText)findViewById(R.id.editText1);
arrtime.setText(+hourOfDay+":"+minute);
}
else if(type.equals("exit") {
arrtime = (EditText)findViewById(R.id.editText2);
exittime.setText(+hourOfDay+":"+minute);
}
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
populateTime(hourOfDay, minute); //changed
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Also delete line android:onClick line from both the ImageButtons in your xml file
Related
I have two textviews and two buttons. When you click on the first button, a window with a choice of time opens. You select the time and it is displayed in textview1. Similarly with the second button and textview2. Now the main task is to sum this time and when you click on the Sum button, display the sum of the time in TextView3 (textview1 + textview2). any ideas how to implement this? preferably with code
XML code:
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is First Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to Second Activity"
android:id="#+id/btnActTwo"
android:onClick="onClick">
</Button>
<TextView
android:id="#+id/viewTime1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time1" />
<Button
android:id="#+id/time1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Time 1"
android:onClick="setTime"/>
<TextView
android:id="#+id/viewTime2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time2" />
<Button
android:id="#+id/time2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Time 2"
android:onClick="setTime2"
/>
<TextView
android:id="#+id/sum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sum" />
<Button
android:id="#+id/btnSum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SUM"
android:onClick="onClick2"/>
</LinearLayout>
And Main.java code:
package com.example.myapplication_lab4;
import androidx.appcompat.app.AppCompatActivity;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView viewTime1;
TextView viewTime2;
TextView sum;
Button time1;
Button time2;
Button btnSum;
Calendar dateAndTime=Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewTime1 = (TextView) findViewById(R.id.viewTime1);
viewTime2 = (TextView) findViewById(R.id.viewTime2);
sum = (TextView) findViewById(R.id.sum);
time1 = (Button) findViewById(R.id.time1);
time2 = (Button) findViewById(R.id.time2);
btnSum = (Button) findViewById(R.id.btnSum);
}
// display a dialog box for selecting the time for 1
public void setTime(View v) {
new TimePickerDialog(MainActivity.this, t,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE), true)
.show();
}
// display a dialog box for selecting the time for 2
public void setTime2(View v) {
new TimePickerDialog(MainActivity.this, t2,
dateAndTime.get(Calendar.HOUR_OF_DAY),
dateAndTime.get(Calendar.MINUTE), true)
.show();
}
// setting start time for 1
private void setInitialDateTime() {
viewTime1.setText(DateUtils.formatDateTime(this,
dateAndTime.getTimeInMillis(),
DateUtils.FORMAT_SHOW_TIME));
}
// setting start time for 2
private void setInitialDateTime2() {
viewTime2.setText(DateUtils.formatDateTime(this,
dateAndTime.getTimeInMillis(),
DateUtils.FORMAT_SHOW_TIME));
}
// setting the time picker for 1
TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
setInitialDateTime();
}
};
// setting the time picker for 2
TimePickerDialog.OnTimeSetListener t2 = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
dateAndTime.set(Calendar.MINUTE, minute);
setInitialDateTime2();
}
};
//irrelevant to the issue
//Click to go to Activity 2
public void onClick(View view) {
Button btnActTwo;
btnActTwo = (Button) findViewById(R.id.btnActTwo);
if (view.getId() == R.id.btnActTwo) {//call sec act
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
public void onClick2(View view) {
}
}
Here is sample code of sum two date.
String time1="0:30:32";
String time2="0:35:20";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
Log.e("TAG", "Date sum is => " + date3);
**Output: ** Date sum is => 01:05:52
I have a really interesting problem with my Navigator menu. I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image. I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
image - this trouble
image - can't click
this my code :
menu_bar.java
package com.database.m.lyburan;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.database.m.lyburan.adapter.EventAdapter;
import com.database.m.lyburan.app.AppController;
import com.database.m.lyburan.data.EventData;
import com.database.m.lyburan.util.Server;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.database.m.lyburan.Buddies.TAG_MESSAGE;
import static com.database.m.lyburan.Login.TAG_USERNAME;
import static com.database.m.lyburan.R.id.parent;
public class menu_bar extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
FragmentManager fragmentManager;
Fragment fragment = null;
ListView list;
SharedPreferences sharedpreferences;
SwipeRefreshLayout swipe;
List<EventData> eventList = new ArrayList<EventData>();
private static final String TAG = menu_bar.class.getSimpleName();
private static String url_list = Server.URL + "event.php?offset=";
private int offSet = 0;
int no;
EventAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
private Boolean isFabOpen = false;
private FloatingActionButton fab, fab1, fab2;
private CardView card1, card2;
private Animation fab_open, fab_close, rotate_forward, rotate_backward, card_open, card_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bar);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
fragment = new Root();
callFragment(fragment);
}
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
list = (ListView) findViewById(R.id.list_event);
eventList.clear();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(menu_bar.this, Buddies.class);
intent.putExtra(TAG_ID, eventList.get(position).getId());
startActivity(intent);
}
});
adapter = new EventAdapter(menu_bar.this, eventList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callEvent(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
Button meet_buddies = (Button) findViewById(R.id.meet_buddies);
meet_buddies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,Buddies.class);
startActivity(intent);
}
});
Button upcoming = (Button) findViewById(R.id.upcoming);
upcoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,asd.class);
startActivity(intent);
}
});
fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
card1 = (CardView) findViewById(R.id.card1);
card2 = (CardView) findViewById(R.id.card2);
/*kenalkan animasi*/
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_backward);
card_open=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_open);
card_close=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_close);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animateFAB();
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(menu_bar.this,Addhome.class);
startActivity(intent);
}
});
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menu_bar.this, "New Call", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bar, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_payment) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_help) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.btn_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Action Settings", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_containers, fragment)
.commit();
}
public void animateFAB() {
/*jika fab dalam keadaan false*/
if (isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
card1.startAnimation(card_close);
card2.startAnimation(card_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
} else {
/*jika dalam keadaan true*/
fab.startAnimation(rotate_forward);
fab1.startAnimation(fab_open);
fab2.startAnimation(fab_open);
card1.startAnimation(card_open);
card2.startAnimation(card_open);
fab1.setClickable(true);
fab2.setClickable(true);
isFabOpen = true;
}
}
#Override
public void onRefresh() {
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
private void callEvent(int page){
swipe.setRefreshing(true);
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
EventData news = new EventData();
no = obj.getInt(TAG_NO);
news.setId(obj.getString(TAG_ID));
news.setJudul(obj.getString(TAG_JUDUL));
if (!Objects.equals(obj.getString(TAG_GAMBAR), "")) {
news.setGambar(obj.getString(TAG_GAMBAR));
}
news.setDatetime(obj.getString(TAG_TGL));
news.setIsi(obj.getString(TAG_ISI));
// adding news to news array
eventList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
activity_menu_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layouts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_menu_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/meet_buddies"
android:layout_width="fill_parent"
android:drawableLeft="#drawable/ic_profil_w"
android:background="#color/ijo"
android:textColor="#android:color/background_light"
android:layout_height="wrap_content"
android:padding="15dp"
android:onClick="meet"
android:layout_marginTop="70dp"
android:text="Meet Buddies"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/upcoming"
android:layout_width="170dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Notification"
android:layout_marginTop="135dp" />
<Button
android:id="#+id/myshared"
android:layout_width="190dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="135dp"
android:text="My Shared"
/>
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:stateListAnimator="#null"
android:src="#drawable/ic_plus_w"
app:backgroundTint="#color/colorAccent"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="130dp"
android:stateListAnimator="#null"
android:layout_marginRight="#dimen/fab_margin"
android:visibility="invisible"
android:src="#drawable/ic_menu_camera"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="140dp"
android:layout_marginRight="75dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Event" />
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="80dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_beranda"
android:visibility="invisible"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="90dp"
android:layout_marginRight="70dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Homestay" />
</android.support.v7.widget.CardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="198dp" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_marginTop="222dp"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_event"
android:layout_width="wrap_content"
android:layout_height="330dp"
android:divider="#null"
android:dividerHeight="2dp"
android:layout_marginTop="222dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
i've tried, how can i fix it ? anyone please help me. thanks.
Anyone else having similar problem. It appears the order in the XML matters too.
I had my NavigationView and after it I had a layout included and I couldn't click an item on the NavigationView.
After I switched them, so that my layout was being included AND THEN AFTER IT I had my NavigationView, it worked ...
this adapter.java
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataModel> item;
public Adapter(Activity activity, List<DataModel> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_buddies, null);
TextView txt_nama = (TextView) convertView.findViewById(R.id.custom_list_item_text1);
txt_nama.setText(item.get(position).getNama());
return convertView;
}
}
You need to create this type of your layout xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
</android.support.v4.widget.DrawerLayout>
In FrameLayout you need to replace all fragment one by one like
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Note: You can write your Coordinator layout and other in fragment itself, may be helpful for you.
I am new over...
My question is: how to obtain the data from the edittext in fragments? I have really tried everything I have been seeking and no result.
Here is the code:
XML Files
register_user.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include layout="#layout/toolbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/secondary_dark"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
fragment_pdata.xml
<RelativeLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.fundacioncanihua.inutritionist.rnp.Fragments.PersonalDataFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pData"
android:layout_marginTop="10dp"
android:textSize="40dp"
android:textStyle="bold"
android:id="#+id/textView"/>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_lastname"
android:theme="#style/TextLabel"
android:layout_below="#+id/textView"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_lName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/lName"
android:inputType="text"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_user"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_firstname"
android:theme="#style/TextLabel"
android:layout_below="#+id/flayout_lastname"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_fName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/fName"
android:inputType="text|textCapWords"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_user"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<LinearLayout android:layout_width="match_parent"
android:id="#+id/fHorizontal"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/flayout_firstname"
android:layout_marginTop="10dp">
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_birthday"
android:theme="#style/TextLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/birthday"
android:inputType="date"
android:drawableLeft="#drawable/ic_edittext_bd"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_gender"
android:theme="#style/TextLabel"
android:layout_width="150dp"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/gender"
android:inputType="text|textCapSentences"
android:maxLength="1"
android:drawableLeft="#drawable/ic_edittext_gender"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/flayout_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:layout_below="#id/fHorizontal"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/input_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/location"
android:inputType="text|textCapWords"
android:maxLength="25"
android:drawableLeft="#drawable/ic_edittext_location"
android:drawablePadding="20dp"/>
</android.support.design.widget.TextInputLayout>
Java Classes
Register Patient
public class RegisterPatient extends AppCompatActivity implements PersonalDataFragment.getEditText {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_data,
R.drawable.ic_tab_measures,
R.drawable.ic_tab_clinical
};
String s_lname;
private ConnectionSQL dataBase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_user);
dataBase = new ConnectionSQL(getApplicationContext());
//Setting up the toolbar
Toolbar toolBar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case R.id.action_settings:
//Code
break;
case R.id.regbutton:
registerPatient();
break;
}
return super.onOptionsItemSelected(item);
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PersonalDataFragment(), getString(R.string.pData));
adapter.addFragment(new AnthropometryFragment(), getString(R.string.anthro));
adapter.addFragment(new NutritionalClinicalFragment(), getString(R.string.nutcli));
viewPager.setAdapter(adapter);
}
private void registerPatient() {
try {
/*final String s_lName = i_lName.getText().toString();
final String s_fName = i_fName.getText().toString();
final String s_bday = i_bday.getText().toString();
final String s_gender = i_gender.getText().toString();
final String s_location = i_location.getText().toString();
dataBase.addPatient(s_lName, s_fName, s_bday, s_gender, s_location);*/
Toast.makeText(RegisterPatient.this, "Patient added successfully!", Toast.LENGTH_SHORT).show();
clearForm((ViewGroup) findViewById(R.id.registerlayout));
} catch (Exception e) {
Toast.makeText(RegisterPatient.this, "Something were wrong! Try it again.", Toast.LENGTH_SHORT).show();
Log.w("WARNING", e.getMessage());
Log.w("WARNING_INFO", e.getCause());
}
}
private void clearForm(ViewGroup group)
{
for (int i = 0, count = group.getChildCount(); i < count; ++i) {
View view = group.getChildAt(i);
if (view instanceof EditText) {
((EditText)view).setText("");
}
if(view instanceof ViewGroup && (((ViewGroup)view).getChildCount() > 0))
clearForm((ViewGroup)view);
}
}
#Override
public void onFragmentEditTextChanged(String lname) {
}
}
PersonalDataFragment.java
public class PersonalDataFragment extends Fragment{
public EditText editText;
public Calendar myCalendar;
public DatePickerDialog.OnDateSetListener uDate;
private getEditText listener = null;
public PersonalDataFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pdata, null);
//Calendar
editText = (EditText) v.findViewById(R.id.input_birthday);
final EditText i_lname = (EditText) v.findViewById(R.id.input_lName);
editText.setTextIsSelectable(true);
myCalendar = Calendar.getInstance();
uDate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vi) {
// TODO Auto-generated method stub
new DatePickerDialog(getActivity(), uDate, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
//Getting EditTexts
i_lname.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
if (listener != null) {
final String stg = i_lname.getText().toString();
listener.onFragmentEditTextChanged(stg);
Toast.makeText(getActivity(), stg, Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
#Override
public void onAttach(Context context) {
listener = (getEditText) context;
}
private void updateLabel() {
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
editText.setText(sdf.format(myCalendar.getTime()));
}
public interface getEditText {
public void onFragmentEditTextChanged(String lname);
}
}
I don't know what I am doing wrong. I need to get access to those EditText in order to user them and add the user to the SQLite DB but, as the EditText are in the Fragment, I cannot access them directly from the RegisterUser class.
Any ideas on how to solve this? I shall be really and deeply thankful.
Thanks in advance.
Try doing like this,
TextInputLayout FlayoutBirthday= (TextInputLayout) v.findViewById(R.id.flayout_birthday);
EditText i_lname = FlayoutBirthday.getEditText();
My app shuts down when clicking a button, anyone knows why? And if you fins any errors please tell me ;)This activity is about two buttons that when pressed show a TimePickerDialog and save the time.
Here's my code:
package app.alexdickson.com.workout1;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
ImageButton botoFlexio;
ImageButton botoAbdominals;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
int hourDefinitivaFlexio;
int minuteDefinitvaFlexio;
int hourDefinitivaAbs;
int minuteDefinitivaAbs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
botoFlexio = (ImageButton) findViewById(R.id.botoFlexio);
botoAbdominals = (ImageButton) findViewById(R.id.botoAbdominals);
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.botoFlexio:
botoFlexio.setBackgroundResource(R.drawable.flexioclicat);
showDialog(DIALOG_ID);
hourDefinitivaFlexio = hour_x;
minuteDefinitvaFlexio = minute_x;
break;
case R.id.botoAbdominals:
botoFlexio.setBackgroundResource(R.drawable.abdominalsclicat);
showDialog(DIALOG_ID);
hourDefinitivaAbs = hour_x;
minuteDefinitivaAbs = minute_x;
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new TimePickerDialog(Main2Activity.this, kTimePickerListener, hour_x, minute_x, true);
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x = hourOfDay;
minute_x = minute;
Toast.makeText(Main2Activity.this, hour_x + ": " + minute_x, Toast.LENGTH_LONG).show();
}
};
And here's my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:orientation="horizontal"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoAbdominals"
android:background="#drawable/abdominals"
android:contentDescription="ImatgeAbdominals"
android:layout_marginTop="50dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
<ImageButton
android:layout_width="0dp"
android:layout_height="400dp"
android:layout_weight="1"
android:id="#+id/botoFlexio"
android:layout_gravity="top"
android:layout_marginTop="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/flexio"
android:contentDescription="ImatgeFlexio"
/>
Thanks for your help !!!!
Register listener with your Button after initialize it.
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
You need to set listeners to the ImageButtons.
For example:
#Override
protected void onCreate(Bundle savedInstanceState) {
....
botoFlexio.setOnClickListener(this);
botoAbdominals.setOnClickListener(this);
}
I have created the start of an item/amount list with EditText fields but would like it so the total sits directly under the amount and for every new item/amount I add, they would sit just underneath the item/amount above them and the total would then jump down to sit under the newest amount field.
xml
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.paulk.homebillcalc.HomeBills" >
<TextView
android:id="#+id/monthNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="86dp"
android:layout_marginStart="86dp"
android:layout_marginTop="31dp"
android:text="#string/month" />
<Spinner
android:id="#+id/monthchooser"
android:entries="#array/months_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="23dp"
android:layout_toEndOf="#+id/monthNameTextView"
android:layout_toRightOf="#+id/monthNameTextView"
android:prompt="#string/months" />
<TextView
android:id="#+id/PoundSign"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/itemAmountText"
android:layout_alignBottom="#+id/itemAmountText"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_toLeftOf="#+id/itemAmountText"
android:layout_toStartOf="#+id/itemAmountText"
android:text="#string/pound_sign"
android:textSize="20sp" />
<Button
android:id="#+id/addItemButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="#string/add_item" />
<EditText
android:id="#+id/itemAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/monthchooser"
android:layout_marginTop="26dp"
android:layout_toEndOf="#+id/addItemButton"
android:layout_toRightOf="#+id/addItemButton"
android:ems="5"
android:hint="#string/item_amount"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/PoundSign1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/totalAmountText"
android:layout_alignBottom="#+id/totalAmountText"
android:layout_toLeftOf="#+id/totalAmountText"
android:layout_toStartOf="#+id/totalAmountText"
android:text="#string/pound_sign"
android:textSize="20sp" />
<EditText
android:id="#+id/itemNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/PoundSign"
android:layout_alignBottom="#+id/PoundSign"
android:layout_toLeftOf="#+id/addItemButton"
android:layout_toStartOf="#+id/itemAmountText"
android:ems="8"
android:hint="#string/item_name"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/totalAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/itemAmountText"
android:layout_alignEnd="#+id/itemAmountText"
android:layout_alignLeft="#+id/itemAmountText"
android:layout_below="#+id/itemAmountText"
android:layout_marginTop="18dp"
android:ems="5"
android:hint="#string/total_amount"
android:inputType="numberDecimal" />
</RelativeLayout>
Code
package com.paulk.homebillcalc;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class HomeBills extends ActionBarActivity implements OnClickListener{
private final static String MONTH_OF_YEAR = "MONTH_OF_YEAR";
private final static String NAME_OF_ITEM = "NAME_OF_ITEM";
private final static String ITEM_AMOUNT = "ITEM_AMOUNT";
private final static String TOTAL = "TOTAL";
private Spinner monthChooser;
private String itemName;
private double itemAmount;
private double total;
EditText itemNameEdit;
EditText itemAmountEdit;
EditText totalEdit;
Button addField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_bills);
addListenerToMonthSelector();
addListenerOnButton();
//if new session
if(savedInstanceState ==null){
itemName = "";
itemAmount = 0;
total = 0;
}else{
//if its a saved session
itemName = savedInstanceState.getString(NAME_OF_ITEM);
itemAmount = savedInstanceState.getDouble(ITEM_AMOUNT);
total = savedInstanceState.getDouble(TOTAL);
}
itemNameEdit = (EditText) findViewById(R.id.itemNameText);
itemAmountEdit = (EditText) findViewById(R.id.itemAmountText);
totalEdit = (EditText) findViewById(R.id.totalAmountText);
addField = (Button) findViewById(R.id.addItemButton);
addField.setOnClickListener(this);
itemAmountEdit.addTextChangedListener(itemAmountListener);
}
private TextWatcher itemAmountListener = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
itemAmount = Double.parseDouble(s.toString());
}catch(Exception e){
itemAmount = 0;
}
updateTotalAmount();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
private void updateTotalAmount() {
//the pulls out the characters from the field, and converts the double value to a string
double itemAmount = Double.parseDouble(itemAmountEdit.getText().toString());
double total = itemAmount;
totalEdit.setText(String.format("%.02f", total));
}
private void addListenerOnButton() {
monthChooser = (Spinner) findViewById(R.id.monthchooser);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_bills, menu);
return true;
}
public void addListenerToMonthSelector(){
monthChooser = (Spinner) findViewById(R.id.monthchooser);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v == addField){
itemNameEdit = (EditText) findViewById(R.id.itemNameText);
itemAmountEdit = (EditText) findViewById(R.id.itemAmountText);
itemAmountEdit.setVisibility(View.VISIBLE);
}
}
}