在tabhost中从tab1导航到选项卡2时发出警报

时间:2017-09-21 07:20:52

标签: android

我有一个tabhost布局。如果用户不选择选项卡1中的列表项,则用户不应导航到选项卡2.如果他尝试导航到选项卡2,则应在选项卡1上显示警告,说明选择选项卡1中的列表项

请帮忙。

感谢

tab.class

package hello.com.navigationdrawer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.TabActivity;
import android.content.Intent;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;


public class Tab extends TabActivity{
    /** Called when the activity is first created. */
    TabHost tabHost;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_new);

        TabHost tabHost = getTabHost();
        TabHost.TabSpec spec;


        //home
        this.setNewTab(this, tabHost, "tab1", R.string.homestr,R.drawable.hom, Home.class);
       this.setNewTab(this, tabHost, "tab2", R.string.planstr,R.drawable.plan, Planning.class);

        this.setNewTab(this, tabHost, "tab3", R.string.repstr,R.drawable.dash,Reports.class);
        this.setNewTab(this, tabHost, "tab3", R.string.searstr,R.drawable.sear, Search.class);


    }

    private void setNewTab(Context context, TabHost tabHost, String tag, int title, int icon, Class content){
        Intent intent;
        TabHost.TabSpec tabSpec;

        if(tag!="tab2"){
        tabSpec = tabHost.newTabSpec(tag);
        tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), title, icon)); // new function to inject our own tab layout
        /*intent = new Intent().setClass(context,content).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);*/
        intent = new Intent().setClass(context,content);
        tabSpec.setContent(intent);
        tabHost.addTab(tabSpec);}
        else{
         tabSpec = tabHost.newTabSpec(tag);
         tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), title, icon)); // new function to inject our own tab layout
        intent = new Intent().setClass(context,content).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        /* intent = new Intent().setClass(context,content);*/
         tabSpec.setContent(intent);
         tabHost.addTab(tabSpec);
     }


        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String value = extras.getString("tab_index");
            if(value.equals("1")){
               tabHost.setCurrentTab(Integer.valueOf(value));
            }

          /*   if(value.equals("2")){

                 tabSpec.setIndicator(getTabIndicator(tabHost.getContext(), title, icon)); // new function to inject our own tab layout
        intent = new Intent().setClass(context,content).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
              *//*   intent = new Intent().setClass(context,content);*//*
                 tabSpec.setContent(intent);
                 tabHost.addTab(tabSpec);
             }*/




        }




    }


    private View getTabIndicator(Context context, int title, int icon) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_activity, null);
        ImageView iv = (ImageView) view.findViewById(R.id.imageView);
        iv.setImageResource(icon);
        TextView tv = (TextView) view.findViewById(R.id.oppercent);
        tv.setText(title);
        tv.setTextColor(getResources().getColorStateList(R.color.tab_txtcolor));

        return view;
    }

    }

Home.class(这是标签1)这是列表所在的标签需要在此活动中显示警告框

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        loggedUser=(TextView) findViewById(R.id.loggeduser);
     /*   loggedUser.setText("Welcome:"+" "+Login.login_user.replace("_"," "));*/
        loggedUser.setVisibility(View.INVISIBLE);
        prolistlabel=(TextView)findViewById(R.id.prolistlabel);
        projects=(ListView) findViewById(R.id.homelist);
        prolistlabel.setVisibility(View.INVISIBLE);
        projects.setVisibility(View.INVISIBLE);
        home_view=(View) findViewById(R.id.homeview);
        home_view.setVisibility(View.INVISIBLE);
        /*requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setProgressBarIndeterminateVisibility(true);*/
        linlaHeaderProgress=(ProgressBar) findViewById(R.id.homeprogress);



        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        logout=(ImageButton)findViewById(R.id.logout_home);
        logout.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                startActivity(new Intent(Home.this,Login.class));
                overridePendingTransition(R.anim.left_right,R.anim.right_left);

            }
        });
        sp=getSharedPreferences(preference, Context.MODE_PRIVATE);


        new ProgressSpin().execute();




    }


    public String webServiceCall() throws Exception {




        URL obj=new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");
        String uname=Login.login_user;
        String pswd=Login.login_pswd;
        String Authentication=uname+":"+pswd;
        try {
            byte[] data = Authentication.getBytes("UTF-8");
            authorisation = Base64.encodeToString(data, Base64.DEFAULT);
            System.out.println("authorisation value"+ authorisation);
        }
        catch(Exception ae){
            ae.printStackTrace();
        }


        //add request header
        con.setRequestProperty("authorisation",authorisation);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        resp=response.toString();
        //print result
        System.out.println("JSON response"+resp);
        return resp;
    }

    public String webservice_call_displayname() throws Exception {




        URL obj=new URL(display_name_url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");
        String uname=Login.login_user;
        String pswd=Login.login_pswd;
        String Authentication=uname+":"+pswd;
        try {
            byte[] data = Authentication.getBytes("UTF-8");
            authorisation = Base64.encodeToString(data, Base64.DEFAULT);
            System.out.println("authorisation value"+ authorisation);
        }
        catch(Exception ae){
            ae.printStackTrace();
        }


        //add request header
        con.setRequestProperty("authorisation",authorisation);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        name_resp=response.toString();
        //print result
        System.out.println("JSON response"+resp);
        return name_resp;
    }
    public void display_name(String resp){
        try{
            JSONObject mainobj=new JSONObject(resp);
            if(mainobj!=null){
              login_user=mainobj.getString("displayName");
                loggedUser.setText(" "+"Welcome:"+" "+login_user);
            }
        }
     catch(Exception e){

     }

    }


    public String resp(String resp){
        String listid;

        adapter=new ArrayAdapter<String>(this,R.layout.listitem,R.id.txt_lan);

        try {
            final JSONArray array = new JSONArray(resp);
            for(int i=0; i<array.length(); i++) {
                JSONObject jsonObj = array.getJSONObject(i);

                name=jsonObj.getString("name");
                adapter.add(name);
                projects.setAdapter(adapter);
                projects.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                System.out.println("name"+name);
                System.out.println("Array length"+ array.length());
                projects.setOnItemClickListener(new AdapterView.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        view.setSelected(true);
                        TextView txt=(TextView)view.findViewById(R.id.txt_lan);
                        String selectedItem=txt.getText().toString();
                        /*String selectedItem=((TextView)view).getText().toString();*/
                        if(selectedItems.contains(selectedItem)){
                            selectedItems.remove(selectedItem);
                        }
                        else
                            selectedItems.add(selectedItem);
                        System.out.println("list view item to be saved is" +selectedItem);
                        System.out.println("list id to be saved is" +position);
                        try {

                            System.out.println("Item form the array" +array.getJSONObject(position).getString("id"));

                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString(saveIt, selectedItem);
                            editor.putString(savePass,array.getJSONObject(position).getString("id"));
                            editor.putString(projKey,array.getJSONObject(position).getString("key"));
                            editor.commit();
                            if(sp.contains(saveIt) && sp.contains(savePass)){
                                saved_project_name=sp.getString(saveIt, "");
                                savedid=sp.getString(savePass, "");
                                savedproid=sp.getString(projKey, "");
                                System.out.println("saved value"+ saved_project_name);
                                System.out.println("saved value"+savedid);
                                System.out.println("saved project key value"+ savedproid);
                            }

                            ((TabActivity) getParent()).getTabHost().setCurrentTab(1);
                          /*
                            finish();
                            startActivity(getIntent());*/


                        }

                        catch(JSONException ae){
                            ae.printStackTrace();
                        }
                    }
                });
            }
        }
        catch(JSONException e){
            // get the name from data.
        }
        return name;
    }

    private class ProgressSpin extends AsyncTask<String,Integer,Void> {
        @Override
        protected void onPreExecute() {
            // SHOW THE SPINNER WHILE LOADING FEEDS
            linlaHeaderProgress.setVisibility(View.VISIBLE);
        }
        @Override
        protected Void doInBackground(String... params) {
          try {
              json_displayname=webservice_call_displayname();
            Jsonresp= webServiceCall();}catch(Exception ae){
              ae.printStackTrace();
          }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            resp(Jsonresp);
            display_name(json_displayname);
            linlaHeaderProgress.setVisibility(View.GONE);
            prolistlabel.setVisibility(View.VISIBLE);
            home_view.setVisibility(View.VISIBLE);
            projects.setVisibility(View.VISIBLE);
            loggedUser.setVisibility(View.VISIBLE);
        }




    }


}

1 个答案:

答案 0 :(得分:1)

如果您使用的是viewPager,请使用此

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            viewPager.setCurrentItem(2); //Second Tab Position
         }
      })
         // Create the AlertDialog object and return it
         return builder.create();
      }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

更改此部分代码

 Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String value = extras.getString("tab_index");
            if(value.equals("1")){
               tabHost.setCurrentTab(Integer.valueOf(value));
            }

到此代码

 Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String value = extras.getString("tab_index");
            if(value.equals("1")){
               tabHost.setCurrentTab(Integer.valueOf(value));
            }else{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
         tabHost.setCurrentTab(Integer.valueOf(value));
         }
      })
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {

         });
         // Create the AlertDialog object and return it
         return builder.create();
      }
}