android - 退出对话框 fragment 后如何更新 MainActivity 中的 TextView?

标签 android android-layout android-fragments android-view android-timepicker

目前,我的主要 Activity 显示任意时间,并按住一个按钮,按下该按钮会弹出一个时间选择器对话框 fragment 。用户在 fragment 中设置新时间并关闭 fragment 后,我希望我的主要 Activity 用用户选择的新时间更新它的 TextView。

我现在的问题是我不知道如何在用户设置时间后更新 Activity 中显示的时间。我试过使用 onResume,但它一直导致应用程序崩溃。退出 fragment 后刷新 Activity 的最佳方式是什么?

我试图实现的流程是用户在 fragment 中设置时间,导致共享首选项更新,然后主 Activity 刷新,用所选时间更新 TextView 。我是不是想错了?

这是我的 TimePickerFragment 类:

package com.example.habitabilitystudy;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements
        TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        Context context = getActivity();
        SharedPreferences sharedPref = context.getSharedPreferences(
                "prediction", Context.MODE_PRIVATE);

        final Calendar c = Calendar.getInstance();
        int defaultHour = c.get(Calendar.HOUR_OF_DAY);
        int defaultMinute = c.get(Calendar.MINUTE);

        int hour = sharedPref.getInt("prediction_hour", defaultHour);
        int minute = sharedPref.getInt("prediction_min", defaultMinute);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        Context context = getActivity();
        SharedPreferences sharedPref = context.getSharedPreferences(
                "prediction", Context.MODE_PRIVATE);
        SharedPreferences.Editor editorh = sharedPref.edit();
        editorh.putInt("prediction_hour", hourOfDay);
        editorh.commit();
        SharedPreferences.Editor editorm = sharedPref.edit();
        editorm.putInt("prediction_min", minute);
        editorm.commit();
        mCallbacks.TimeUpdated();

    }

    /**
     * Interface
     */
    private FragmentCallbacks mCallbacks;

    public interface FragmentCallbacks {
        void TimeUpdated();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (FragmentCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(
                    "Activity must implement Fragment Two.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

}

我的主要 Activity :

package com.example.habitabilitystudy;

import java.util.Calendar;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements
        TimePickerFragment.FragmentCallbacks {

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

        // Use the current time as the default values for the picker
        SharedPreferences sharedPref = this.getSharedPreferences("prediction",
                Context.MODE_PRIVATE);

        final Calendar c = Calendar.getInstance();
        int defaultHour = c.get(Calendar.HOUR_OF_DAY);
        int defaultMinute = c.get(Calendar.MINUTE);

        int hour = sharedPref.getInt("prediction_hour", defaultHour);
        int minute = sharedPref.getInt("prediction_min", defaultMinute);

        String timeString = Integer.toString(hour) + ":"
                + Integer.toString(minute);

        TextView predictionText = (TextView) findViewById(R.id.prediction_time);
        predictionText.setText(timeString);
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    @Override
    public void TimeUpdated() {
        Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
    }

    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.predictButton:
            startActivity(new Intent(this, MainActivity.class));
            break;
        case R.id.login:
            startActivity(new Intent(this, LoginActivity.class));
            break;
        }
    }
}

我的主要 Activity xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/prediction_time"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingRight="3dip"
        android:background="#5c755e"
        android:gravity="end"
        android:textColor="#3d4935"
        android:textSize="25sp"
        android:textStyle="italic"
        android:text="(c) appsrox.com" /> 


    <Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:text="@string/adjust_time" 
    android:onClick="showTimePickerDialog" />



</RelativeLayout>

最佳答案

您想在对话框 fragment 中创建一个界面。选择时间后,它将通知 Activity 。如果这给您带来任何问题,请告诉我。

fragment

public class TimePickerFragment extends DialogFragment implements
    TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        Context context = getActivity();
        SharedPreferences sharedPref = context.getSharedPreferences(
            "prediction", Context.MODE_PRIVATE);

        final Calendar c = Calendar.getInstance();
        int defaultHour = c.get(Calendar.HOUR_OF_DAY);
        int defaultMinute = c.get(Calendar.MINUTE);

        int hour = sharedPref.getInt("prediction_hour", defaultHour);
        int minute = sharedPref.getInt("prediction_min", defaultMinute);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
            DateFormat.is24HourFormat(getActivity()));
    }


    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        Context context = getActivity();
        SharedPreferences sharedPref = context.getSharedPreferences(
            "prediction", Context.MODE_PRIVATE);
        SharedPreferences.Editor editorh = sharedPref.edit();
        editorh.putInt("prediction_hour", hourOfDay);
        editorh.commit();
        SharedPreferences.Editor editorm = sharedPref.edit();
        editorm.putInt("prediction_min", minute);
        editorm.commit();
        mCallbacks.TimeUpdated(hourOfDay, minute);
    }

    /**
     * Interface
     */
    private FragmentCallbacks mCallbacks;

    public interface FragmentCallbacks {
        void TimeUpdated(int hour, int minute);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (FragmentCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement Fragment Two.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

}

主 Activity

public class MainActivity extends Activity implements TimePickerFragment.FragmentCallbacks {

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

        // Use the current time as the default values for the picker
        SharedPreferences sharedPref = this.getSharedPreferences("prediction",
            Context.MODE_PRIVATE);

        final Calendar c = Calendar.getInstance();
        int defaultHour = c.get(Calendar.HOUR_OF_DAY);
        int defaultMinute = c.get(Calendar.MINUTE);

        int hour = sharedPref.getInt("prediction_hour", defaultHour);
        int minute = sharedPref.getInt("prediction_min", defaultMinute);

        String timeString = Integer.toString(hour) + ":"
            + Integer.toString(minute);

        TextView predictionText = (TextView) findViewById(R.id.prediction_time);
        predictionText.setText(timeString);
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    @Override
    public void TimeUpdated(int hour, int minute) {
        Toast.makeText(this, "Hour: " + hour + " Minute: " + minute, Toast.LENGTH_SHORT).show();
        String timeString = Integer.toString(hour) + ":" + Integer.toString(minute);
        TextView predictionText = (TextView) findViewById(R.id.prediction_time);
        predictionText.setText(timeString);
    }
}

关于android - 退出对话框 fragment 后如何更新 MainActivity 中的 TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585173/

相关文章:

android - 如何将手机的屏幕坐标映射到电脑屏幕?

Android:从线程更新用户界面

java - Android aar 库不包含依赖项

android - 如果为空,则更改 ListView 布局

Android GridView 全屏

android - 在 fragment 中设置新布局

java - Android Studio - fragment onClickListener 不工作

android - 如何检测 AdWhirl 广告是否加载失败?

android - 仅带有图标的滑动 TabLayout

java - FragmentTransaction.add() : wrong Fragment type