设置Android按钮单击后退按钮上的监听器事件单击Android片段

时间:2017-07-03 08:28:38

标签: android xml fragment

Profile.java

package com.synergywebdesigners.veebee;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Profile extends AppCompatActivity {
    public TextView user,pass,email,mob,add;
    public Button ChangePass;
    FragmentManager fragmentManager = Profile.this.getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        final FrameLayout frame = (FrameLayout) findViewById(R.id.chg_frag);
        user = (TextView) findViewById(R.id.user);
        pass = (TextView) findViewById(R.id.pass);
        email = (TextView) findViewById(R.id.email);
        mob = (TextView) findViewById(R.id.mob);
        add = (TextView) findViewById(R.id.add);
        ChangePass = (Button) findViewById(R.id.chang_pass);
        ChangePass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChangPass changPass = new ChangPass();
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.chg_frag,changPass);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                fragmentTransaction = fragmentManager.beginTransaction();
                ScrollView scrollView = (ScrollView) findViewById(R.id.scroll);
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String user = sharedPreferences.getString(Config.USERNAME_SHARED_PREF,"Not Available");
        String url = Config.DATA_URL+user;

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //loading.dismiss();
                showJSON(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // Toast.makeText(Profile.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
    private void showJSON(String response){
        String users="";
        String passw="";
        String emails = "";
        String mobile = "";
        String address = "";
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
            JSONObject collegeData = result.getJSONObject(0);
            users = collegeData.getString(Config.KEY_UNAME);
            passw = collegeData.getString(Config.KEY_PASS);
            emails = collegeData.getString(Config.KEY_EMAIL);
            mobile = collegeData.getString(Config.KEY_MOB);
            address = collegeData.getString(Config.KEY_ADD);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        user.setText("User :\t"+users);
        pass.setText("Password :\t"+passw);
        email.setText("Email Id :\t"+emails);
        mob.setText("Mob No :\t"+mobile);
        add.setText("Address :\t"+address);
    }
    //Logout function
    private void logout(){
        //Creating an alert dialog to confirm logout
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure you want to logout?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                        //Getting out sharedpreferences
                        SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
                        //Getting editor
                        SharedPreferences.Editor editor = preferences.edit();

                        //Puting the value false for loggedin
                        editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);

                        //Putting blank value to email
                        editor.putString(Config.USERNAME_SHARED_PREF, "");

                        //Saving the sharedpreferences
                        editor.commit();

                        //Starting login activity
                        Intent intent = new Intent(Profile.this, LoginActivity.class);
                        startActivity(intent);
                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });

        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Adding our menu to toolbar
        getMenuInflater().inflate(R.menu.vee_bee, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_logout) {
            //calling logout method when the logout button is clicked
            logout();
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/scroll"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none"
    android:background="@drawable/side_nav_bar"
    tools:context="com.synergywebdesigners.veebee.Profile">
    <RelativeLayout
        android:id="@+id/profile_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/margin_header"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/margin_header"
        android:background="@drawable/side_nav_bar">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:orientation="vertical"
            android:id="@+id/linearLayout1"
            android:gravity="center">
            <TextView
                android:id="@+id/user_profile_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="@string/name"
                android:textAllCaps="true"
                android:textColor="@color/defaults"
                android:textSize="20sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/user_profile_short_bio"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/user_profile_name"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="12dp"
                android:text="@string/web_add"
                android:textColor="@color/defaults"
                android:textSize="14sp" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:textColor="@color/defaults"
                android:textStyle="bold"
                android:clickable="true"
                android:textAllCaps="true"
                android:id="@+id/m_org"
                android:gravity="center"
                android:visibility="invisible"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_below="@id/user_profile_short_bio"/>

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:orientation="vertical"
            android:id="@+id/linearLayout"
            android:layout_below="@+id/linearLayout1">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/defaults"
            android:clickable="true"
            android:elevation="4dp"
            android:padding="@dimen/fab_margin"
            android:id="@+id/user" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_marginBottom="3dp"
            android:layout_marginTop="3dp"
            android:background="@color/defaults"
            android:clickable="true"
            android:elevation="4dp"
            android:padding="@dimen/fab_margin"
            android:id="@+id/pass"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/defaults"
            android:clickable="true"
            android:elevation="4dp"
            android:padding="@dimen/fab_margin"
            android:id="@+id/email"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/defaults"
            android:clickable="true"
            android:elevation="4dp"
            android:padding="@dimen/fab_margin"
            android:id="@+id/mob"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/defaults"
            android:clickable="true"
            android:elevation="4dp"
            android:padding="@dimen/fab_margin"
            android:id="@+id/add"/>
        </LinearLayout>
        <Button
            android:id="@+id/chang_pass"
            android:layout_below="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_header"
            android:background="@color/colorPrimaryDark"
            android:textColor="@color/defaults"
            android:textAllCaps="true"
            android:textStyle="bold"
            android:text="Change Password"/>
     <FrameLayout
         android:layout_below="@id/chang_pass"
         android:id="@+id/chg_frag"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"/>
    </RelativeLayout>
</ScrollView>

ChangePass.java

package com.synergywebdesigners.veebee;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
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.EditText;
import android.widget.Toast;

import java.util.HashMap;


public class ChangPass extends Fragment {
 public EditText PrevPass,NewPass;
    public Button Conform;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_chang_pass,container,false);
        PrevPass = (EditText) view.findViewById(R.id.prev_pass);
        NewPass = (EditText) view.findViewById(R.id.new_pass);
        Conform = (Button) view.findViewById(R.id.send);
        Conform.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ChangePass();
                //getActivity().finish();

            }
        });
        return view;

    }
    private void ChangePass(){
        class Addmessage extends AsyncTask<Void,Void,String> {
            ProgressDialog loading;
            SharedPreferences sharedPreferences = getContext().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
            String user = sharedPreferences.getString(Config.USERNAME_SHARED_PREF,"Not Available");
            String prevpass = PrevPass.getText().toString().trim();
            String newpass = NewPass.getText().toString().trim();
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(getActivity(),"Sending Request..","..Please..Wait..",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(getActivity(),s,Toast.LENGTH_SHORT).show();
            }

            @Override
            protected String doInBackground(Void... v) {

                HashMap<String,String> params = new HashMap<>();
                params.put(Config.KEY_PASS_USER,user);
                params.put(Config.KEY_PREV_PASS,prevpass);
                params.put(Config.KEY_NEW_PASS,newpass);
                ReuestHandler rh = new ReuestHandler();
                String res = rh.sendPostRequest(Config.URL_CHANG_PASS, params);
                return res;
            }
        }
        Addmessage ae = new Addmessage();
        ae.execute();
    }
}

fragment_chang_pass.xml

<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"
tools:context="com.synergywebdesigners.veebee.ChangPass">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <TextView
        android:id="@+id/lbl_prev"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/defaults"
        android:textStyle="bold"
        android:text="Your Current Password"/>
        <EditText
            android:id="@+id/prev_pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:layout_below="@+id/lbl_prev"
            android:singleLine="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Password"
        android:textColor="@color/defaults"
        android:id="@+id/lbl_new"
        android:textStyle="bold"
        android:layout_below="@+id/prev_pass"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
        <EditText
            android:id="@+id/new_pass"
            android:inputType="text"
            android:singleLine="true"
            android:layout_below="@+id/lbl_new"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
       <Button
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:id="@+id/send"
           android:padding="10dp"
           android:layout_below="@+id/new_pass"
           android:textColor="@color/defaults"
           android:background="@color/colorPrimary"
           android:text="Confirm Password Change"
           />
    </RelativeLayout>
</FrameLayout>

在代码中,我想添加Conform按钮点击监听器事件调用Android后退按钮。就像在此时点击片段关闭片段中的后退按钮一样。

2 个答案:

答案 0 :(得分:0)

public void pushFragment(Fragment fragment, boolean shouldAdd, Bundle bundle) {
        stackFragmentMain.push(fragment);
        FragmentManager man = getSupportFragmentManager();
        FragmentTransaction ft = man.beginTransaction();
        ft.replace(R.id.main_screens, fragmentholder.fragment);
        ft.commitAllowingStateLoss();
    }

    public void popFragment() {
        if (stackFragmentMain.size() >= 1) {
            Fragment fragment = stackFragmentMain
                    .elementAt(stackFragmentMain.size() - 2);
            stackFragmentMain.pop();
            if (fragmentholder != null) {
                FragmentManager man = getSupportFragmentManager();
                FragmentTransaction ft = man.beginTransaction();
                ft.replace(R.id.main_screens, fragmentholder.fragment);
                ft.commitAllowingStateLoss();
            }
        }
    }

答案 1 :(得分:-1)

修改

更改LabelRange方法的以下部分: -

onClick

 ChangPass changPass = new ChangPass();
            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.chg_frag,changPass);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
            fragmentTransaction = fragmentManager.beginTransaction();

编辑2

在上述更改的同时,在 ChangPass changPass = new ChangPass(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.chg_frag,changPass); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); fragmentManager.executePendingTransactions(); 片段的Conform.onClickListener()中添加以下代码: -

ChangePass