将Android活动类转换为Android片段类代码

时间:2014-01-04 07:50:07

标签: java android android-fragments

以下是我尝试convert我的代码从activity扩展类到fragment的代码,但似乎很难。

我可以请求帮助吗?

活动Java代码

@SuppressLint("NewApi")
public class FileComplaintActivity extends Activity {

    private Button buttonSubmit;
    private EditText editTextName;
    private EditText editTextComplaint;
    //private EditText editTextPlateNo;
    Bitmap thumbnail;
    File pic;
    private EditText editTextEmail;
    private EditText editTextNo;
    private Button button1;

    private final static String PREFERENCE_USER = "user";

    private Spinner spinnerComplaintType;
    private Spinner spinnerVehicleType;
    private EditText editTextBodyNo;
    private EditText editTextPlateNo;
    private EditText editTextLocation;
    private EditText editTextDate;
    private EditText editTextComplaintDetails;

    private String username;
    private String complaintType;
    private String vehicletype;
    private String date;

    private int year;
    private int month;
    private int day;
    static final int DATE_PICKER_ID = 1111; 

    private static final int CAMERA_PIC_REQUEST = 1111;
    private ImageView imageViewPhotoReport;

    String imageString;

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

    private void initViews() {
        // TODO Auto-generated method stub
        buttonSubmit = (Button)findViewById(R.id.buttonSubmit);

        username= getUsername();

        editTextBodyNo = (EditText)findViewById(R.id.editTextBodyNo);
        editTextPlateNo = (EditText)findViewById(R.id.editTextPlate);
        editTextLocation = (EditText)findViewById(R.id.editTextLocation);
        editTextDate = (EditText)findViewById(R.id.editTextDate);
        editTextComplaintDetails = (EditText)findViewById(R.id.editTextComplaintDetails);


        button1 = (Button)findViewById(R.id.button1);

        spinnerComplaintType = (Spinner)findViewById(R.id.spinnerComplaintType);
        ArrayAdapter<CharSequence> adapterComplaint = ArrayAdapter.createFromResource(getBaseContext(), R.array.complaintType, android.R.layout.simple_list_item_1);
        spinnerComplaintType.setAdapter(adapterComplaint);
        spinnerComplaintType.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                complaintType = parent.getItemAtPosition(position).toString();
            //  Toast.makeText(getApplicationContext(), complaintType, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });

        spinnerVehicleType = (Spinner)findViewById(R.id.spinnerVehicleType);
        ArrayAdapter<CharSequence> adapterVehicle = ArrayAdapter.createFromResource(getBaseContext(), R.array.vehicleType, android.R.layout.simple_list_item_1);
        spinnerVehicleType.setAdapter(adapterVehicle);
        spinnerVehicleType.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                vehicletype = parent.getItemAtPosition(position).toString();
            //  Toast.makeText(getApplicationContext(), vehicletype, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });


        final Calendar c = Calendar.getInstance();
        year  = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day   = c.get(Calendar.DAY_OF_MONTH);

        editTextDate.setText(new StringBuilder()
        // Month is 0 based, just add 1
        .append(year)
        .append("-")
                .append(month + 1)
                .append("-").append(day));

        imageViewPhotoReport=(ImageView)findViewById(R.id.imageViewPhotoReport);

    }
    public void buttonDateClicked(View view){
        showDialog(DATE_PICKER_ID);
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_PICKER_ID:

            // open datepicker dialog. 
            // set date picker for current date 
            // add pickerListener listner to date picker
            return new DatePickerDialog(this, pickerListener, year, month,day);
        }
        return null;
    }
    private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {

            year  = selectedYear;
            month = selectedMonth;
            day   = selectedDay;

            // Show selected date 
            editTextDate.setText(new StringBuilder()
            .append(year)
            .append("-")
                    .append(month + 1)
                    .append("-").append(day)
                    );
           }
        };

    @SuppressLint("UnlocalizedSms")
    public void buttonClickSubmit(View view){
        Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_SHORT).show();
        SmsManager smsManager =     SmsManager.getDefault();
//      smsManager.sendTextMessage("+639177260573", null, "HAHAHAH", null, null);

        smsManager.sendTextMessage("+639178866281", null, "Name: "+editTextName.getText().toString()+" Plate No: "+ editTextPlateNo.getText().toString() + " Complaint: "+editTextComplaint.getText().toString(), null, null);
        //finishAffinity();
        //Toast.makeText(getApplicationContext(), editTextNo.getText().toString(), Toast.LENGTH_SHORT).show();
    }
    private String getUsername() {
        SharedPreferences preference = getSharedPreferences(PREFERENCE_USER,
                MODE_PRIVATE);
         username = preference.getString("username", "");
        if (!username.isEmpty()) {
            return username;
        }
        return "";
    }
    public void buttonClickEmail(View view){
        String to = "olannataniel@yahoo.com";
          String subject = editTextName.getText().toString();
          String message = editTextComplaint.getText().toString();

          Intent email = new Intent(Intent.ACTION_SEND);
          email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
          //email.putExtra(Intent.EXTRA_CC, new String[]{ to});
          //email.putExtra(Intent.EXTRA_BCC, new String[]{to});
          email.putExtra(Intent.EXTRA_SUBJECT, subject);
          email.putExtra(Intent.EXTRA_TEXT, message);

          //need this to prompts email client only
          email.setType("message/rfc822");

          startActivity(Intent.createChooser(email, "Choose an Email client :"));

        }
    public void buttonSendClick(View view){
        final Calendar c = Calendar.getInstance();
           int yyyy = c.get(Calendar.YEAR);
           int mm = c.get(Calendar.MONTH);
           int dd = c.get(Calendar.DAY_OF_MONTH);
           date = yyyy + "-" + (mm+1) + "-" + dd;
        SendComplaintTask task = new SendComplaintTask();
        try {
            String status = task.execute().get();
            Toast.makeText(this, status, Toast.LENGTH_SHORT).show();
        //  Intent intent = new Intent(this, LoginActivity.class);


        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    public class SendComplaintTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... arg0) {

            String url = getResources().getString(R.string.url_addComplaint);



    //     Toast.makeText(getApplicationContext(), yyyy + "-" + mm + "-" + dd, Toast.LENGTH_SHORT).show();

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();

            pairList.add(new BasicNameValuePair("complaintType", complaintType));
            pairList.add(new BasicNameValuePair("vehicleType", vehicletype));
            pairList.add(new BasicNameValuePair("bodyNo", editTextBodyNo
                    .getText().toString()));
            pairList.add(new BasicNameValuePair("plateNo", editTextPlateNo
                    .getText().toString()));
            pairList.add(new BasicNameValuePair("complaintLocation", editTextLocation
                    .getText().toString()));
            pairList.add(new BasicNameValuePair("complaintDate", editTextDate
                    .getText().toString()));
            pairList.add(new BasicNameValuePair("complaintDetails", editTextComplaintDetails
                    .getText().toString()));
            pairList.add(new BasicNameValuePair("complaintImage", imageString));
            pairList.add(new BasicNameValuePair("dateFiled", date.toString()));
            pairList.add(new BasicNameValuePair("username", username));


            try {
                post.setEntity(new UrlEncodedFormEntity(pairList));
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                String line = "";
                String json = "";
                while ((line = reader.readLine()) != null) {
                    json += line + System.getProperty("line.separator");
                }
                Log.i("asdf", json);
                JSONObject jsonObject = new JSONObject(json);
                String status = jsonObject.getString("status");
                return status;

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

    }
    public void buttonTakePhoto(View view){

        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA_PIC_REQUEST);
    }

     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == CAMERA_PIC_REQUEST) {
                //2
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");  
                imageViewPhotoReport.setImageBitmap(thumbnail);
                imageViewPhotoReport.setVisibility(1);

                //3
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                //4 
                File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
                try {
                    file.createNewFile();
                    FileOutputStream fo = new FileOutputStream(file);
                    //5
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                imageString = Base64.encodeToString(bytes.toByteArray(), 
                        Base64.NO_WRAP);
               // Toast.makeText(getApplicationContext(), "TEST: " + imageString, Toast.LENGTH_SHORT).show();
                editTextComplaintDetails.setText(imageString);
            }
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.create_report, menu);
        return true;
    }

}

这是我最初的片段代码

public class WhatsHotFragment extends Fragment {

        public WhatsHotFragment(){}

        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);
        return rootView;
    }

}

2 个答案:

答案 0 :(得分:3)

what i want to ask is that how can i implement initViews() function in Activity to Fragment

所以

Buttom button
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);
    return rootView;
}

覆盖onActivityCreated

然后

  button = (Button)getView()findViewById(R.id.buttonSubmit);
  // similarly for other views 

初始化onActivitedCreated中的视图没有任何害处。

您还可以在onCreateView

中初始化视图
Buttom button
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);
    button = button = (Button)getView()findViewById(R.id.buttonSubmit);
    // similarly for other views 
    return rootView;
}

了解更多信息

http://developer.android.com/guide/components/fragments.html

答案 1 :(得分:2)

片段生命周期与Activity生命周期略有不同。 虽然片段包含onCreate()onStart()onResume()等方法,但这些方法与活动的方法相同,但我们设置的片段不同。

片段在其onCreateView()方法中对其用户界面进行了膨胀,该方法返回View。 之后,我们会在onViewCreated()进一步设置。 (例如,设置onClickListeners等)。

当然,你可以在这里找到这一切:http://developer.android.com/guide/components/fragments.html

修改 尽管可以在onActivityCreated()中设置子视图,但最好在onViewCreated()中进行设置,因为onViewCreated()旨在执行此操作,因此它更符合文档。