0

Android 新手并尝试根据共享偏好设置 view.GONE。然而它并没有消失!我打破了什么?!

编辑所以,在测试了底层问题之后,设置没有正确完成......所以现在已经修复了,让我们再试一次。他是我的 onCreate... 当我删除 textview 临时代码时,它工作正常并通过 toast 显示 pref 的更改,但是当它那里的代码时,应用程序崩溃。

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            // Inflate the layout for this fragment      

            Boolean symptothermal = mPreferences.getBoolean("symptothermal", true);

            if (!symptothermal) {
                Context context = getActivity().getApplicationContext();
                Toast.makeText(context, "Hello toast 1!", Toast.LENGTH_LONG).show();
            } else {
                Context context = getActivity().getApplicationContext();
                Toast.makeText(context, "Hello toast 2!", Toast.LENGTH_LONG).show();
            }

            if (!symptothermal) {
                TextView temp = (TextView) getView().findViewById(R.id.temp);
                temp.setVisibility(View.GONE);
            }
        }

他是 XML 仅供参考:

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

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.23" >

        <!-- Date Text -->
        <EditText
            android:id="@+id/dateselected"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="10dp"
            android:layout_toLeftOf="@+id/pickdate"
            android:gravity="center"
            android:inputType="date" />

        <!-- DatePicker button -->
        <Button
            android:id="@+id/pickdate"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/dateselected"
            android:layout_alignBottom="@+id/dateselected"
            android:layout_alignParentRight="true"
            android:src="@drawable/ic_datepicker"
            android:text="@string/date" />

        <!-- Temp Label -->
        <EditText
            android:id="@+id/temp"
            android:layout_width="192dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/pickdate"
            android:ems="10"
            android:inputType="text"
            android:text="@string/temp"
            android:clickable="false" 
            android:cursorVisible="false" 
            android:focusable="false" 
            android:focusableInTouchMode="false" 
            android:layout_marginTop="10dp">
        </EditText>

         <!-- Temp field -->
        <EditText
            android:id="@+id/tempvalue"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/pickdate"
            android:layout_toRightOf="@+id/dateselected"
            android:ems="10"
            android:inputType="number"
            android:layout_marginTop="10dp" />

    </RelativeLayout>

    <!-- Notes Field -->

    <EditText
        android:id="@+id/chartingnote"
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="0.58"
        android:ems="20"
        android:gravity="top|center_horizontal"
        android:hint="@string/hintNote"
        android:inputType="textMultiLine" />

    <!-- Update Button -->

    <Button
        android:id="@+id/chartingupdate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/charting_update" />

</LinearLayout>

编辑@daniel_c05:

        package com.projectcaruso.naturalfamilyplaning;

        import com.projectcaruso.naturalfamilyplanning.R;

        import android.app.DatePickerDialog.OnDateSetListener;
        import android.content.Context;
        import android.content.SharedPreferences;
        import android.os.Bundle;
        import android.preference.PreferenceManager;
        import android.support.v4.app.Fragment;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.DatePicker;
        import android.widget.TextView;
        import android.widget.Toast;

        public class ChartingFragment extends Fragment implements OnDateSetListener {
            SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            Boolean symptothermal = mPreferences.getBoolean("symptothermal", true);

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
            }    

            public void showDatePickerDialog(View v) {
                DatePickerFragment newFragment = new DatePickerFragment();
                newFragment.show(getChildFragmentManager(), "datePicker");
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);


                if (!symptothermal) {
                    Context context = getActivity().getApplicationContext();
                    Toast.makeText(context, "Hello toast 1!", Toast.LENGTH_LONG).show();
                } else {
                    Context context = getActivity().getApplicationContext();
                    Toast.makeText(context, "Hello toast 2!", Toast.LENGTH_LONG).show();
                }
            }



            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                //Inflate a view
                View view = inflater.inflate(R.layout.fragment_charting, null);
                //now you can initialize the TextView
                //notice how we don't call getView()? :P
                TextView temp = (TextView) view.findViewById(R.id.temp);
                if (!symptothermal) {
                //Hide the view if necessary
                        temp.setVisibility(View.GONE);
                    }
                return view;
               }


        }

日志:

    05-08 14:10:55.042: E/AndroidRuntime(22900): FATAL EXCEPTION: main
    05-08 14:10:55.042: E/AndroidRuntime(22900): java.lang.NullPointerException
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:371)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:366)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at com.projectcaruso.naturalfamilyplaning.ChartingFragment.<init>(ChartingFragment.java:21)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at com.projectcaruso.naturalfamilyplaning.MenuFragment.onListItemClick(MenuFragment.java:36)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.widget.AbsListView$1.run(AbsListView.java:3423)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.os.Handler.handleCallback(Handler.java:725)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.os.Handler.dispatchMessage(Handler.java:92)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.os.Looper.loop(Looper.java:137)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at android.app.ActivityThread.main(ActivityThread.java:5041)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at java.lang.reflect.Method.invokeNative(Native Method)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at java.lang.reflect.Method.invoke(Method.java:511)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    05-08 14:10:55.042: E/AndroidRuntime(22900):    at dalvik.system.NativeStart.main(Native Method)
4

5 回答 5

1

您试图在创建视图之前将视图设置为消失,您的 onCreateView 尚未返回任何内容,但是在它完成inflater.inflate并返回视图之后。onStart您应该改为在方法中执行该检查。

于 2013-05-07T19:59:38.310 回答
1

根据我的理解,您正在为此代码使用片段。

因此,请注意片段的生命周期与活动的生命周期不同。在onCreate无法操作片段上的 UI 元素期间。

你用这个:

 if (!symptothermal) {
            TextView temp = (TextView) getView().findViewById(R.id.temp);
            temp.setVisibility(View.GONE);
        }

稍微改一下吧

第一步:更改Boolean symptothermal为实例变量,而不是onCreate. 因此,使其在不同的生命周期中可用。

第二步: 保留相同的代码onCreate,除了您不调用更改 TextView 可见性的代码这一事实,我们将把它移到其他地方。

第三步:改为覆盖 onCreateView。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    //Inflate a view
    View view = inflater.inflate(R.layout.your_layout, null);
    //now you can initialize the TextView
    //notice how we don't call getView()? :P
    TextView temp = (TextView) view.findViewById(R.id.temp);
    if (!symptothermal) {
    //Hide the view if necessary
            temp.setVisibility(View.GONE);
        }
    return view;
   }

那应该很好用。

编辑

所以我注意到你这样做了:

SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
Boolean symptothermal = mPreferences.getBoolean("symptothermal", true);

这就是问题所在,您在任何生命周期之外调用 getDefaultSharedPreferences ,这就是它失败的原因。

看到这个:

public class ChartingFragment extends Fragment implements OnDateSetListener {
//Don't initialize the instance variables yet
   SharedPreferences mPreferences;
   Boolean symptothermal;

@Override
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
     //Here's a good moment to initialize
    mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    symptothermal = mPreferences.getBoolean("symptothermal", true);

        if (!symptothermal) {
            Context context = getActivity().getApplicationContext();
            Toast.makeText(context, "Hello toast 1!", Toast.LENGTH_LONG).show();
        } else {
            Context context = getActivity().getApplicationContext();
            Toast.makeText(context, "Hello toast 2!", Toast.LENGTH_LONG).show();
        }
    }
}
于 2013-05-08T13:55:26.127 回答
0

观察你onCreate()有一些事情对我来说没有任何意义。

使用Boolean symptothermal = preferences.getBoolean("symptothermal", true);将始终返回true。您设置true为默认值,我没有看到您的代码中 variablesymptothermal设置为的任何部分false,这意味着您的 if 语句将永远不会被执行。你有没有试过做if(symptothermal)而不是?(只需确保它可以使用默认值)。

此外,TextView temp = (TextView) getView().findViewById(R.id.temp);会使您的应用程序崩溃ClassCastException!为什么?因为您的临时 id 视图不是 aTextView而是EditText.

让我知道你的进展。

于 2013-05-07T20:59:25.443 回答
0

onCreateView()用于创建视图。返回时onCreateView,创建视图。有一种方法onViewCreated用于修改视图。

文档中的更多信息: Fragment#onViewCreated

于 2013-05-07T20:03:42.720 回答
0

您永远不会将 TextView 的可见性设置为 GONE,因为您的if陈述是错误的:您设置了一个值而不是检查它。你应该做:

if (symptothermal == false)

或者

if (!symptothermal)
于 2013-05-07T20:10:08.693 回答