简体   繁体   English

我如何将两个活动从我的代码转换为两个片段

[英]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) 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) 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

    <?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购买布局.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 .您需要的是Viewpager

Please look into this tutorial http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/请查看本教程http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/

This serves your purpose.这符合你的目的。

To learn more about ViewPager .了解更多关于ViewPager

Here is a example to How to use fragments in a Activity and how to switch them.以下是如何在 Activity 中使用片段以及如何切换它们的示例。

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:和 SignUpActivity.xml 文件:

<?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:和 nameFragment 类:

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.在那里你可以创建任何你想要的 Fragment 类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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