在android studio中处理片段中的片段

时间:2017-01-17 09:08:09

标签: java android android-fragments

我需要帮助我的logoutButton片段onclick听众。我想清除我的共享偏好并制作一个意图。我已经阅读了很多关于SO的问题,但我无法解决这个问题。我在我的应用程序的活动中尝试过它,但它不起作用。

有很多错误:

  • 在我的按钮声明上:无法解析方法findViewById(int)
  • 在我的共享偏好设置中:无法解析方法getSharedPreferences(java.lang.String, int)
  • finish()声明:无法解决方法finish()
  • 在我的new Intent构造函数中:无法解析构造函数Intent(de.myfirstapp.app.SettingsFragment, java.lang.Class<de.myfirstapp.app.LoginActivity>)

&#13;
&#13;
package de.myfirstapp.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;

import static android.content.Context.MODE_PRIVATE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SettingsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SettingsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SettingsFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public SettingsFragment() {
        // Required empty public constructor
    }

    //Change the title in action bar
    public void onResume(){
        super.onResume();
        String titleString = getResources().getString(R.string.title_activity_navigation_drawer_settings);
        // Set title bar
        ((NavigationDrawerActivity) getActivity())
                .setActionBarTitle(titleString);
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SettingsFragment newInstance(String param1, String param2) {
        SettingsFragment fragment = new SettingsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        //Logout button interaction
        Button logoutButton = (Button) findViewById(R.id.logoutButton);

        //Set onclick listener for the logout button
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Deleting shared preferences for login activity
                SharedPreferences loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = loginPreferences.edit();
                editor.clear();
                editor.commit();
                finish();

                // Launching login activity screen
                Intent intentLogout = new Intent(SettingsFragment.this, LoginActivity.class);
                SettingsFragment.this.startActivity(intentLogout);
            }

            ;
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_settings, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onStart() {
        super.onStart();
        try {
            mListener = (OnFragmentInteractionListener) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

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

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
&#13;
&#13;
&#13;

您可以在onCreate(Bundle savedInstanceState)方法中找到我的onClick方法。谢谢你帮助我摆脱黑暗:)

6 个答案:

答案 0 :(得分:2)

  1. 使用onCreateView(..)代替onCreate()

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
        Button your_button = (Button) view.findViewById(R.id.your_button);
        //...
    }
    
  2. 如果您想从上下文中使用任何内容,请使用getContext()。然后,您可以拨打getContext().getSharedPreferences()或新Intent(getContext(), ...)。如果您想从父Activity拨打任何内容,请通过回调拨打电话或通过Activity使用getActivity()实例。例如:getActivity().finish()

  3. 但所有这些都是基础知识,您应该阅读FragmentSupport Fragment

答案 1 :(得分:1)

$json = [ 'query' => [ 'bool' => [ 'must_not' => [ ['terms' => ['_id' => []]], ['terms' => ['rarity' => []]] ], 'must' => [ 'range' => [ 'disappearTime' => [ 'gte' => 'now', 'lte' => 'now+1d' ] ] ], 'filter' => [ ['term' => ['pokemon_id' => 16]], [ 'geo_bounding_box' => [ 'location' => [ 'top_left' => [ 'lat' => 52.280577919216356, 'lon' => -113.78533601760866 ], 'bottom_right' => [ 'lat' => 52.26306210545918, 'lon' => -113.81855249404909 ] ] ] ], [ 'geo_polygon' => [ 'location' => [ "points" => [ [-113.78721646175813, 52.29637194474555], [-113.76335508934484, 52.281770664368565], [-113.76335508934484, 52.26112133563143], [-113.78721646175813, 52.24652005525444], [-113.82096153824187, 52.24652005525444], [-113.84482291065517, 52.26112133563143], [-113.84482291065517, 52.281770664368565], [-113.82096153824187, 52.29637194474555], [-113.78721646175813, 52.29637194474555], [-113.69997059121626, 52.298658944745554], [-113.67610798767082, 52.28405766436857], [-113.67610798767082, 52.26340833563143], [-113.69997059121626, 52.248807055254446], [-113.73371740878373, 52.248807055254446], [-113.75758001232917, 52.26340833563143], [-113.75758001232917, 52.28405766436857], [-113.73371740878373, 52.298658944745554], [-113.69997059121626, 52.298658944745554] ] ] ] ] ] ] ] ]; 没有Fragment方法。您应该在充气的视图上使用此方法来创建findViewById

当您为视图充气时,将其保存到字段变量视图,然后通过以下方式初始化视图:

Fragment

答案 2 :(得分:1)

你的`onCreateView中的

声明了如下按钮

View view=inflater.inflate(R.layout.settings,container,false);
Button logoutButton = (Button) view.findViewById(R.id.logoutButton);

finish();使用getActivity.finish();

getActivity.getSharedPreferences用于sharedpref

用于使用本地服务

Intent intentLogout = new Intent(getActivity(), LoginActivity.class);
            getActivity().startActivity(intentLogout);

答案 3 :(得分:1)

将点击代码移动到onCreateView(...)方法,您可以在膨胀视图中找到此按钮,而不是片段本身。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view  =  inflater.inflate(R.layout.fragment_settings, container, false);

    //Logout button interaction
    Button logoutButton = (Button) view.findViewById(R.id.logoutButton);

    //Set onclick listener for the logout button
    logoutButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Deleting shared preferences for login activity
            SharedPreferences loginPreferences = getActivity().getSharedPreferences("loginPrefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = loginPreferences.edit();
            editor.clear();
            editor.commit();
            getActivity().finish();

            // Launching login activity screen
            Intent intentLogout = new Intent(getActivity(), LoginActivity.class);
            SettingsFragment.this.startActivity(intentLogout);
        }

        ;
    });

    return view;
}

如果您之前添加getActivity()方法,其他功能将起作用,例如:     getActivity()。getSharedPreferences(...)

答案 4 :(得分:1)

Fragment有这样的OnCreateView。

    Button logoutButton;

      @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View v = new View(getActivity());//you can access your button like this
logoutButton=(Button)v.findViewById(R.id.logoutButton);


    return v;

请阅读this,你可以理解如何处理碎片。这有助于。:)

答案 5 :(得分:1)

在onCreateView中获取按钮引用

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_settings, container, false);
    logoutButton = (Button) findViewById(R.id.logoutButton);
    return view;
}

要获取共享首选项,请使用

SharedPreferences loginPreferences = getActivity().getSharedPreferences("loginPrefs", MODE_PRIVATE);

要完成活动使用,请在startActivity调用下移动它。

getActivity().finish();

创建意图使用

Intent intentLogout = new Intent(getActivity(), LoginActivity.class);