Integrating google sign in, sign in button visibility not changing on UpdateUI method - android-studio

I am trying to integrate a google sign in feature for my app. Its mostly working fine and I can sign in ok.
However, when the user is signed in, the sign in buttons visibility is supposed to be false, and then a LinearLayout which includes two text views and a log out button is supposed to become visible.
Here is the code of the main layout activity which has all the text views, buttons etc
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/Prof_Pic"
android:layout_width="90dp"
android:layout_height="wrap_content"
tools:srcCompat="#tools:sample/avatars" />
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Display name here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/Email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Display email here"
android:textSize="12dp"
android:textStyle="bold" />
<Button
android:id="#+id/SignOut"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
tools:layout_editor_absoluteX="159dp"
tools:layout_editor_absoluteY="506dp" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"/>
</LinearLayout>
Here is the Main Activity file with all the code
private LinearLayout prof_section;
private LinearLayout LsignIn;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Pic;
private GoogleApiClient GoogleApiClient;
private static final int REQ_CODE = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting variables as correct object
prof_section = (LinearLayout)findViewById(R.id.prof_section);
SignOut = (Button)findViewById(R.id.SignOut);
SignIn = (SignInButton)findViewById(R.id.sign_in_button);
Name = (TextView)findViewById(R.id.Name);
Email = (TextView)findViewById(R.id.Email);
Prof_Pic = (ImageView)findViewById(R.id.Prof_Pic);
//register buttons for onclick listener
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
//setting linearlayout and button to visible/invisible
prof_section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
GoogleSignInOptions SignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail ().build();
GoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_ SIGN_IN_API,SignInOptions).build();
}
protected void onStart() {
super.onStart();
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.sign_in_button:
SignIn();
break;
case R.id.SignOut:
SignOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void SignIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(GoogleApiClient);
startActivityForResult(intent,REQ_CODE);
}
private void SignOut() {
Auth.GoogleSignInApi.signOut(GoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
UpdateUI(false);
}
});
}
private void handleResult(GoogleSignInResult result) {
if(result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
//Glide.vith(this).load(img_url).into(Prof_Pic);
UpdateUI(true);
}
else
{
UpdateUI(false);
}
}
private void UpdateUI(boolean isLogin) {
if(isLogin)
{
prof_section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
}
else
{
prof_section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
Im getting no error messages when I run the app

Since you are calling activitywithresult() function which returns the result, So you will get the result in onActivityResult(). As you are not having any Result handler you are not able to handle the result. You need to add onActivityResult(). If you get the result their, then you have to call your function handleResult() to know whether user is successfully signed in or not.
Just add this code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == REQ_CODE) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleResult(task);
}
}
private void handleResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
//Glide.vith(this).load(img_url).into(Prof_Pic);
UpdateUI(true);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
UpdateUI(false);
}
}

Related

Spinner has data but doesn't have any preview text/selected text

Spinner has data but doesn't have any preview text/selected text I try various things and still doesn't show any text
Im trying to use spinner for some data and I successfully populated some list for spinner data but it doesn't show any in the spinner.
I also try various things i saw from the net and it didnt work.
Here is the link where I based my code for spinner: https://www.youtube.com/watch?v=j7P5k-dHS9Y
JAVA CODE:
public class SpinnerSample extends AppCompatActivity {
Spinner spinner;
boolean isSpinnerTouched = false;
DatabaseReference databaseReference;
String[] status = {"Not Available", "Available", "Under Maintenance"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_sample);
spinner = findViewById(R.id.spiiner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SpinnerSample.this, R.layout.style_spinner, status);
adapter.setDropDownViewResource(R.layout.style_spinner);
spinner.setAdapter(adapter);
databaseReference = FirebaseDatabase.getInstance().getReference();
spinner.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
isSpinnerTouched = true;
return false;
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String value = adapterView.getItemAtPosition(i).toString();
if (!isSpinnerTouched) {
Toast.makeText(SpinnerSample.this, "No Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SpinnerSample.this, value, Toast.LENGTH_SHORT).show();
}
}
});
}
}
XML CODE:
<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"
android:orientation="vertical"
tools:context=".SpinnerSample">
<Spinner
android:id="#+id/spiiner"
android:layout_width="240dp"
android:background="#ff0"
android:layout_height="40dp"
android:textColor="#000"
android:hint="Current Password"
android:layout_marginTop="10dp"/>
</LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:text="A"
android:padding="20dp"
android:layout_height="match_parent"
android:textColor="#000"
android:textColorHint="#1e7591">
</TextView>

Display ImageButton on last slide of viewpager

I'm trying to have a button appear only on the last page of a ViewPager. I have the working button but it is displayed on all the pages instead of only the last page. I want to have it visible only on the last page. Here is my code.
activity_welcome2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".Welcome_Activity"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--- for dots -->
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#+id/dotsLayout"
android:background="#color/white"
android:layout_marginBottom="15dp" />
<LinearLayout
android:id="#+id/dotsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="55sp" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/next3"
android:layout_width="99dp"
android:layout_height="45dp"
android:background="#android:color/transparent"
android:scaleType="fitCenter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.822"
app:srcCompat="#drawable/next" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Welcome_Activity.java
package com.group7.salitongue;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
public class Welcome_Activity extends AppCompatActivity {
private ViewPager mPager;
private int[] layouts = { R.layout.activity_main, R.layout.activity_splashscreen2, R.layout.activity_welcome };
private MpagerAdapter mpagerAdapter;
private LinearLayout Dots_Layout;
private ImageView[] dots;
private ImageButton nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome2);
mPager = (ViewPager) findViewById(R.id.viewPager);
mpagerAdapter = new MpagerAdapter(layouts, this);
mPager.setAdapter(mpagerAdapter);
Dots_Layout = (LinearLayout) findViewById(R.id.dotsLayout);
createDots(0);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
createDots(position);
}
#Override
public void onPageScrollStateChanged(int state) {}
});
// transition button to Signup page
nextBtn = (ImageButton) findViewById(R.id.next3);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Welcome_Activity.this,MainActivity.class);
startActivity(intent);
}
});
}
private void createDots(int current_position) {
if(Dots_Layout != null)
Dots_Layout.removeAllViews();
dots = new ImageView[layouts.length];
for (int i = 0; i < layouts.length; i++) {
dots[i] = new ImageView(this);
if (i == current_position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots));
}
else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.default_dots));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
Dots_Layout.addView(dots[i],params);
}
}
}
How can I display the button only when the user has reached the last page of swiping?
Just listen in the onPageSelected method of your OnPageChangeListener when the last page is reached and set the button to visible. In all other cases, just hide it.
#Override
public void onPageSelected(int position) {
createDots(position);
// only show the button when the last page is reached
if (position == mPagerAdapter.getCount() - 1)
nextBtn.setVisibility(View.VISIBLE);
else
nextBtn.setVisibility(View.GONE);
}

Recycle View android Studio search well but just shows 1 item

Here a beginner at Android studio.
I'm creating a simple agenda app, where you can add, edit, delete and search contacts.
I used a recycle view but after adding the search option, the recycle view just shows me one contact.
The contacts are being added as appear when I search for them.
Any idea on how to fix it?
It tried changing the layout but nothing works.
My main activity.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<SearchView
android:id="#+id/txtBuscar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listacontactos"
android:layout_width="match_parent"
android:layout_height="591dp" />
</LinearLayout>
</LinearLayout>
Here is the Adapter: https://github.com/soymartanegro/agendaApp/blob/main/src/main/java/com/example/agenda/adaptadores/ListaContactosAdapter.java
Main Java: https://github.com/soymartanegro/agendaApp/blob/main/src/main/java/com/example/agenda/MainActivity.java
Thanks a lot.
I have used the below code it's working perfectly. Please check it. Currently, I'm using dummy data for testing purposes.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<SearchView
android:id="#+id/txtBuscar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listacontactos"
android:layout_width="match_parent"
android:layout_height="591dp" />
</LinearLayout>
</LinearLayout>
lista_item_contacto.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/viewNombre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
contactos
public class contactos {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ListaContactosAdapter.java
public class ListaContactosAdapter extends RecyclerView.Adapter<ListaContactosAdapter.ContactoViewHolder> {
ArrayList<contactos> listaContactos;
ArrayList<contactos> listaOriginal;
public ListaContactosAdapter(ArrayList<contactos> listaContactos){
this.listaContactos = listaContactos;
listaOriginal = new ArrayList<>();
listaOriginal.addAll(listaContactos);
}
#NonNull
#Override
public ContactoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_item_contacto, null , false);
return new ContactoViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ContactoViewHolder holder, int position) {
holder.viewName.setText(listaContactos.get(position).getName());
}
public void filtrado(String txtBuscar){
int longitud = txtBuscar.length();
if (longitud == 0){
listaContactos.clear();
listaContactos.addAll(listaOriginal);
} else {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
List<contactos> collecion = listaContactos.stream().filter(i->i.getName().toLowerCase().contains(txtBuscar.toLowerCase()))
.collect(Collectors.toList());
listaContactos.clear();
listaContactos.addAll(collecion);
} else {
for(contactos c: listaOriginal){
if (c.getName().toLowerCase().contains(txtBuscar.toLowerCase())){
listaContactos.add(c);
}
}
}
}
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return listaContactos.size();
}
public class ContactoViewHolder extends RecyclerView.ViewHolder {
TextView viewName, viewTelephone, viewEmail;
public ContactoViewHolder(#NonNull View itemView) {
super(itemView);
viewName = itemView.findViewById(R.id.viewNombre);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
}
});
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{
SearchView txtBuscar;
RecyclerView listaContactos;
ArrayList<contactos> listaArrayContactos;
ListaContactosAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtBuscar = findViewById(R.id.txtBuscar);
listaContactos = findViewById(R.id.listacontactos);
listaContactos.setLayoutManager(new LinearLayoutManager(this));
listaArrayContactos = new ArrayList<>();
contactos c1 = new contactos();
c1.setName("Hello");
contactos c2 = new contactos();
c2.setName("Android");
contactos c3 = new contactos();
c3.setName("Studio");
listaArrayContactos.add(c1);
listaArrayContactos.add(c2);
listaArrayContactos.add(c3);
adapter = new ListaContactosAdapter(listaArrayContactos);
listaContactos.setAdapter(adapter);
//Revisar si no funciona y cambiar de lugar
txtBuscar.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
adapter.filtrado(s);
return false;
}
}

how to calculate number using SherlockFragment

Hi I am Trying To calculate number like Calculator. the code is working if I use Activity but doesn't work in Sherlock Fragment. I use android:onClick="". Can someone tell what should I do to implement this code. Thank you.
Code :
public class Calculate extends SherlockFragment {
private int resultspinner, inputnumber, totals;
private Spinner spinner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.activity_summary,
container, false);
setSpinnerContent(rootView);
return rootView;
}
private void setSpinnerContent(View view)
{
spinner = (Spinner) view.findViewById( R.id.spinner );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity()
.getBaseContext(),
R.array.pangkat_arrays, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter( adapter );
...
}
// showing a toast on selecting an item
//Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void startcalculate(View view) {
EditText ed_resultspinner = (EditText) getView().findViewById(R.id.EditText1);
EditText ed_input = (EditText) getView().findViewById(R.id.EditText2);
EditText ed_total = (EditText) getView().findViewById(R.id.EditText3);
try {
resultspinner = Integer.parseInt(ed_resultspinner.getText().toString());
inputnumber = Integer.parseInt(ed_input.getText().toString());
totals = resultspinner + inputnumber;
ed_total.setText(String.valueOf(totals));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startcalculate"
android:text="Button" />
Error
java.lang.IllegalStateException: Could not find a method startcalculate(View) in the activity class com.user.learing.MainActivity for onClick handler on view class android.widget.Button with id 'button1'
this is happening because your SherlockFragment class not finding reference onClick for some reason, you have to do is delete the onClick from layout and sets the code manually like this
Button button1 = (Button) view.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your logic
}
});

How do I set a title in my layout with ListView?

I'm trying to implement a ListView with a title. However, with my code below, the following happens :
the title appears over the first list element.
There is a EditText which appears in front of the others on the top.
My android Activity
public class LoanRepaymentActivity extends ListActivity implements View.OnClickListener {
private Location lastKnownLocation;
private ArrayList<CurrentRepaymentInstallment> loansForRepayment;
#Override
public void onCreate(Bundle savedInstanceState){
lastKnownLocation = Utility.getLastKnownLocation(this);
super.onCreate(savedInstanceState);
Intent intent = getIntent();
RepaymentInfo repaymentInfo = (RepaymentInfo)intent.getSerializableExtra(Constants.CURRENT_REPAYMENT_INSTALLMENT);
loansForRepayment = repaymentInfo.getLoansForRepayment();
boolean repaymentsNotPresent = loansForRepayment == null || loansForRepayment.isEmpty();
if(repaymentsNotPresent){
Dialog dialog = Utility.getDialogWithText(LoanRepaymentActivity.this, getText(R.string.noLoansForRepayment).toString());
Utility.getDialogButton(dialog, LoanRepaymentActivity.this, PartnerGroupListActivity.class, intent.getStringExtra(Constants.ACECSS_TOKEN_PARAM));
dialog.show();
}
setContentView(R.layout.loan_repayments);
ArrayAdapter<CurrentRepaymentInstallment> adapter = new LoanRepaymentListAdapter(this, loansForRepayment);
View footer = getLayoutInflater().inflate(R.layout.loan_disbursement_footer, null);
getListView().addFooterView(footer);
setListAdapter(adapter);
if(!repaymentsNotPresent) {
TextView textView = (TextView)findViewById(R.id.screenTitle);
String currentInstallmentLabel = getText(R.string.currentInstallmentLabel).toString() + repaymentInfo.getCurrentGroupInstallment();
textView.setText(currentInstallmentLabel);
}
Button button = (Button)findViewById(R.id.disburse);
button.setOnClickListener(this);
}
The XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView android:id="#+id/screenTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TextView>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+layout/loan_disbursement_footer"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/borrowerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="14sp"
>
</TextView>
<TextView
android:id="#+id/loanAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="14sp"
>
</TextView>
<TextView
android:id="#+id/installmentNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="12sp"
>
</TextView>
<TextView
android:id="#+id/estimatedTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="12sp"
>
</TextView>
</LinearLayout>
<EditText
android:id="#+id/repaymentAmount"
android:layout_width="100sp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:inputType="numberDecimal"
android:textSize="12sp"
>
</EditText>
Custom Array Adapter
public class LoanRepaymentListAdapter extends ArrayAdapter<CurrentRepaymentInstallment> {
private final List<CurrentRepaymentInstallment> loansForRepayment;
private final Activity context;
public LoanRepaymentListAdapter(Activity context, List<CurrentRepaymentInstallment> loansForRepayment) {
super(context, R.layout.loan_repayments, loansForRepayment);
this.context = context;
this.loansForRepayment = loansForRepayment;
}
static class ViewHolder {
protected TextView borrowerName;
protected TextView loanAmount;
protected TextView installmentNumber;
protected TextView estimatedTotal;
protected EditText repaymentAmount;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.loan_repayments, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.borrowerName = (TextView) view.findViewById(R.id.borrowerName);
viewHolder.loanAmount = (TextView) view.findViewById(R.id.loanAmount);
viewHolder.installmentNumber = (TextView) view.findViewById(R.id.installmentNumber);
viewHolder.estimatedTotal = (TextView) view.findViewById(R.id.estimatedTotal);
viewHolder.repaymentAmount = (EditText) view.findViewById(R.id.repaymentAmount);
// viewHolder.repaymentAmount.setEditableFactory(Editable.Factory.getInstance());
viewHolder.repaymentAmount.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String repaymentAmount = s.toString();
try {
loansForRepayment.get(position).setRepaymentAmount(Float.parseFloat(repaymentAmount));
} catch (Exception ex){
loansForRepayment.get(position).setRepaymentAmount(0.0F);
}
}
});
view.setTag(viewHolder);
viewHolder.repaymentAmount.setTag(loansForRepayment.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).repaymentAmount.setTag(loansForRepayment.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.borrowerName.setText(loansForRepayment.get(position).getLoanProfileBasicInfo().getBorrowerBasicInfo().getFirstName());
holder.loanAmount.setText("Rs. " + Float.toString(loansForRepayment.get(position).getLoanProfileBasicInfo().getLoanAmountInPaisa()/100));
holder.estimatedTotal.setText("Rs. " + Float.toString(loansForRepayment.get(position).getEstimatedTotalAmount()/100));
holder.installmentNumber.setText("Inst no : " + Integer.toString(loansForRepayment.get(position).getInstallmentNumber()));
float repaymentAmt = loansForRepayment.get(position).getRepaymentAmount();
if(repaymentAmt != 0.0) holder.repaymentAmount.setText(Float.toString(repaymentAmt));
return view;
}
}
Would be great if someone could tell me how to do this.
Set a new layout for the title and add it to the ListView as a header.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
>
<TextView android:id="#+id/repaymentScreenTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/repaymentsTitle" >
</TextView>
</LinearLayout>
Replace this block with the one below it in your Activity
if(!repaymentsNotPresent) {
TextView textView = (TextView)findViewById(R.id.screenTitle);
String currentInstallmentLabel = getText(R.string.currentInstallmentLabel).toString() + repaymentInfo.getCurrentGroupInstallment();
textView.setText(currentInstallmentLabel);
}
View headerView = getLayoutInflater().inflate(R.layout.loan_repayment_title, null);
TextView titleView = (TextView) headerView.findViewById(R.id.repaymentScreenTitle);
String titlePrefix = (String) getText(R.string.groupInstallmentLabel);
titleView.setText(titlePrefix + " " + repaymentInfo.getCurrentGroupInstallment());
getListView().addHeaderView(headerView);

Resources