简体   繁体   中英

How do i convert the two activities from my code to two Fragments

I need to take the two activities in my code and convert them into two fragments.

These are the requirements:

  1. There will be one application activity that shows the common logo image at the top. Lock the application to display in portrait mode only.

  2. Create two Fragments, one for the data entry and the other for the loan summary display. Each of the fragments will be attached to the application activity directly underneath the logo image as controlled by the options in the Action Bar. There will be two tabs in the Action Bar: Car Purchase and Loan Summary. When Car Purchase is selected, the fragment for data entry should be displayed. When Loan Summary is selected, the loan detail calculated based on the current purchase data should be displayed.

Please help in any way.

Activity1 (LoanSummaryActivity.java)

    package com.cornez.autopurchase;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class LoanSummaryActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loansummary_layout);
    TextView monthlyPayET = (TextView) findViewById(R.id.textView2);
    TextView loanReportET = (TextView) findViewById(R.id.textView3);

    // PASS DATA
    Intent intent = getIntent();

    String report;
    report = intent.getStringExtra("LoanReport");

    String monthlyPay;
    monthlyPay = intent.getStringExtra("MonthlyPayment");
    monthlyPayET.setText(monthlyPay);
    loanReportET.setText(report);
}

public void goDataEntry(View view) {
    finish();
}
}

Activity2 (PurchaseActivity.java)

    package com.cornez.autopurchase;

public class PurchaseActivity extends Activity {
// THE AUTO OBJECT CONTAINS THE INFORMATION ABOUT THE VEHICLE BEING      PURCHASED
Auto mAuto;

// THE DATA TO BE PASSED TO THE LOAN ACTIVITY
String loanReport;
String monthlyPayment;

// LAYOUT INPUT REFERENCES
private EditText carPriceET;
private EditText downPayET;
private RadioGroup loanTermRG;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.purchase_layout);

    //ESTABLISH REFERENCES TO EDITABLE TEXT FIELDS AND RADIO BUTTON
    carPriceET = (EditText) findViewById(R.id.editText1);
    downPayET = (EditText) findViewById(R.id.editText2);
    loanTermRG = (RadioGroup) findViewById(R.id.radioGroup1);

    //CREATE AN AUTOMOBILE OBJECT TO STORE AUTO DATA
    mAuto = new Auto();
}

private void collectAutoInputData() {
    // TASK 1: SET THE CAR PRICE
    mAuto.setPrice ((double) Integer.valueOf(carPriceET.getText()
            .toString()));

    //TASK 2: SET THE DOWN PAYMENT
    mAuto.setDownPayment((double)
            Integer.valueOf(downPayET.getText()
                    .toString()));

    //TASK 3 SET THE LOAN TERM
    Integer radioId = loanTermRG.getCheckedRadioButtonId();
    RadioButton term = (RadioButton) findViewById(radioId);
    mAuto.setLoanTerm(term.getText().toString());
}
private void buildLoanReport() {
    // TASK 1: CONSTRUCT THE MONTHLY PAYMENT
    Resources res = getResources();
    monthlyPayment = res.getString(R.string.report_line1)
            + String.format("%.02f", mAuto.monthlyPayment());


    // TASK 2: CONSTRUCT THE LOAN REPORT
    loanReport = res.getString(R.string.report_line6)
            + String.format("%10.02f", mAuto.getPrice());
    loanReport += res.getString(R.string.report_line7)
            + String.format("%10.02f", mAuto.getDownPayment());

    loanReport += res.getString(R.string.report_line9)
            + String.format("%18.02f", mAuto.taxAmount());
    loanReport += res.getString(R.string.report_line10)
            + String.format("%18.02f", mAuto.totalCost());
    loanReport += res.getString(R.string.report_line11)
            + String.format("%12.02f", mAuto.borrowedAmount());
    loanReport += res.getString(R.string.report_line12)
            + String.format("%12.02f", mAuto.interestAmount());

    loanReport += "\n\n" + res.getString(R.string.report_line8) + " " +                                 mAuto.getLoanTerm() + " years.";

    loanReport += "\n\n" + res.getString(R.string.report_line2);
    loanReport += res.getString(R.string.report_line3);
    loanReport += res.getString(R.string.report_line4);
    loanReport += res.getString(R.string.report_line5);

}

public void activateLoanSummary(View view) {
    //TASK 1: BUILD A LOAN REPORT FROM THE INPUT DATA
    collectAutoInputData();
    buildLoanReport();

    //TASK 2: CREATE AN INTENT TO DISPLAY THE LOAN SUMMARY ACTIVITY
    Intent launchReport = new Intent(this, LoanSummaryActivity.class);

    //TASK 3: PASS THE LOAN SUMMARY ACTIVITY TWO PIECES OF DATA:
    //     THE LOAN REPORT CONTAINING LOAN DETAILS
    //     THE MONTHLY PAYMENT
    launchReport.putExtra("LoanReport", loanReport);
    launchReport.putExtra("MonthlyPayment", monthlyPayment);

    //TASK 4: START THE LOAN ACTIVITY
    startActivity(launchReport);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu;
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@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);
}
}

loansummary_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">

<!-- LOGO AND INSTRUCTION SECTION -->
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:contentDescription="@string/title_activity_main"
    android:src="@drawable/logo" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_alignRight="@+id/imageView1"
    android:layout_below="@+id/imageView1"
    android:background="@color/steel_blue"
    android:gravity="center_horizontal"
    android:text="@string/loan_summary"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="#fff"
    android:textSize="12sp" />

<!-- TEXTVIEW HOLDING THE MONTHLY PAYMENT -->
<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="2dp"
    android:textSize="18sp" />

<!-- TEXTVIEW HOLDING THE CAR LOAN SUMMARY -->
<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="2dp"
    android:textSize="16sp"
    android:typeface="monospace"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="goDataEntry"
    android:text="@string/go_data_entry" />

</RelativeLayout>

purchase_layout.xml

    </RadioGroup>

<TextView
    android:id="@+id/textView6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/radioGroup1"
    android:layout_centerHorizontal="true"
    android:text="@string/loan_term"
    android:textColor="@color/steel_blue"
    android:textSize="12sp"  />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="@string/generate_btn"
    android:onClick="activateLoanSummary"/>

</RelativeLayout>

What you need is called a Viewpager .

Please look into this tutorial http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/

This serves your purpose.

To learn more about ViewPager .

Here is a example to How to use fragments in a Activity and how to switch them.

public class SignUpActivity extends AppCompatActivity {

            private FragmentManager fragmentManager;
            private Fragment switchFragment;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_sign_up);

                fragmentManager = getSupportFragmentManager();

                switchFragment nameFragment = new SignNameFragment();
                fragmentManager.beginTransaction()
                   .add(R.layout.activity_sign_up, switchFragment)
                   .commit();


            }

           public void cambiarFragment(){
                 switchFragment = new anyTypeFragment();
                 fragmentManager.beginTransaction()
                    .replace(R.layout.activity_sign_up, switchFragment)
                    .commit();
              }
    }

and the SignUpActivity.xml file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:id="@+id/activity_sign_up">


</FrameLayout>

and the nameFragment class:

public class nameFragment extends Fragment {

    private Button next;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Inicializar Modelo
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v= inflater.inflate(R.layout.nameFragment_fragment_layout,container,false);    ///Cargar XML, Vista Padre, Si quiero dejarlo siempre

        next=(Button)v.findViewById(R.id.btn_crear_grupo);

        next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                        ((SignUpActivity) getActivity()).cambiarFragment();
                    }


                }
            });



        return v;


    }
}

there you can create any Fragment class you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM