【问题标题】:How to add fragment tab from another activity如何从另一个活动添加片段选项卡
【发布时间】:2017-09-06 17:19:26
【问题描述】:

我正在寻求有关片段的帮助。我的活动和底部导航中显示了 3 个片段。我在底部导航上有一个按钮,带有打开另一个活动的命令,我在其中声明了 ImageViews(我也可以使用 gridview ..)。我想要的是通过单击 ImageView 将片段添加到我的主要活动中。我已经声明了一个片段,它可以使用了。在我的 MainActivity.java 中,我有显示我想要显示多少页(片段选项卡)的代码 - Override public int getCount() { return 3 } - 显示 3 页,当我将其更改为 4 时,第四个片段将被显示。感谢您的回答和帮助!

//edit// 我正在添加每个活动的代码以便更好地理解

MainActivity.java

    package com.example.mp.mmfinal2;


import android.app.Activity;
import android.content.Intent;
import android.media.Image;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.internal.NavigationMenuItemView;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


    static final int TRY_ADD_RESULT = 1;

    protected Integer display_num;


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_fullscreen:
                    Intent intent4=new Intent(MainActivity.this, Main2Activity.class);
                    startActivity(intent4);
                    return true;
                case R.id.navigation_home:
                    Intent intent5=new Intent(MainActivity.this, MainActivity.class);
                    startActivity(intent5);
                    return true;
                case R.id.navigation_add:
                    Intent intent9=new Intent(MainActivity.this, TryAdd.class);
                    startActivityForResult(intent9, TRY_ADD_RESULT);
                    return true;
            }
            return false;
        }

    };

    @Override
    protected void onActivityResult(TRY_ADD_RESULT requestCode, int resultCode, Intent data) {
        if (requestCode == IMAGE_CLICK_RESULT) {
            if(resultCode == Activity.RESULT_OK){
                Integer result=data.getIntExtra("result");
                display_num = result;
                mSectionsPagerAdapter.notifyDataSetChanged();
            }
        }
    }


    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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


        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){

                case 0:
                    Novtab tab1 = new Novtab();
                    return tab1;
                case 1:
                    Hostab tab2 = new Hostab();
                    return tab2;
                case 2:
                    Idntab tab3 = new Idntab();
                    return tab3;
                case 3:
                    Fortab tab4 = new Fortab();
                    return tab4;
                default:
                    return null;


            }
        }



        @Override
        public int getCount() {

            return display_num;

        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Google";
                case 1:
                    return "Seznam";
                case 2:
                    return "Stranka";
                case 3:
                    return "whatever";
            }
            return null;
        }
    }
 }

TryAdd.java (通过点击底部导航项调用的第二个活动)

    package com.example.mp.mmfinal2;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class TryAdd extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private View mControlsView;
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            mControlsView.setVisibility(View.VISIBLE);
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */


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

        setContentView(R.layout.activity_try_add);

        mVisible = true;
        mControlsView = findViewById(R.id.fullscreen_content_controls);
        mContentView = findViewById(R.id.fullscreen_content);


        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.

        ImageView imview3 = (ImageView) findViewById(R.id.imageView3);
        imview3.setClickable(true);
        imview3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent data = new Intent();
                data.putExtra("result", 4);
                setResult(RESULT_OK, data);
                finish();
            }
        });

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mControlsView.setVisibility(View.GONE);
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
}

gridempty.java

package com.example.mp.mmfinal2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class gridempty extends AppCompatActivity {
    GridView gridView;

    String[] values = {
            "Stranka1",
            "Stranka 2"
    } ;

    int[] images = {
            R.drawable.add,
            R.drawable.home
    } ;

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

        gridView = (GridView) findViewById(R.id.griView);
        GridAdapter gridAdapter = new GridAdapter(this, values, images);
        gridView.setAdapter(gridAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            }
        });


    }
}

网格适配器

package com.example.mp.mmfinal2;

import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by mp on 06.09.2017.
 */

public class GridAdapter extends BaseAdapter {



    Context context;
    private final String [] values;
    private final int [] images;
    View view;
    LayoutInflater layoutInflater;

    public GridAdapter(Context context, String[] values, int[] images) {
        this.context = context;
        this.values = values;
        this.images = images;
    }



    @Override
    public int getCount() {
        return values.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if(convertView == null){
            view = new View(context);
            view = layoutInflater.inflate(R.layout.single_item, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
            TextView textview = (TextView) view.findViewById(R.id.textview);
            imageView.setImageResource(images[position]);
            textview.setText(values[position]);


        }
        return view;
    }
}

【问题讨论】:

    标签: java android fragment


    【解决方案1】:

    getCount()中返回一个全局变量并将其值设置为3。单击imageview后将全局变量设置为4并通过调用pagerAdapter.notifyDataSetChanged()刷新适配器数据

    希望对你有帮助:)

    【讨论】:

    • 感谢您的建议,我试过了,但我不知道要编写正确的确切代码,我对 android studio 和 java 了解不多,我两周前开始编写应用程序 :D,感谢您的回答,我在上面的问题中添加了代码,如果您还有时间提供帮助,我将不胜感激!
    【解决方案2】:

    您不能直接编辑另一个活动的成员变量,因为切换到第二个活动会导致第一个活动停止。在您开始第二个活动后,第一个活动实际上不再运行。因此,您的第二个活动必须能够在完成后将其更改传达给第一个活动。我建议调查startActivityForResult。你会做这样的事情:

    活动一:

    public class MainActivity extends AppCompatActivity {
    
    
        static final int TRY_ADD_RESULT = 1;
    
        protected Integer display_num;
    
    
        private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {
    
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_fullscreen:
                        Intent intent4=new Intent(MainActivity.this, Main2Activity.class);
                        startActivity(intent4);
                        return true;
                    case R.id.navigation_home:
                        Intent intent5=new Intent(MainActivity.this, MainActivity.class);
                        startActivity(intent5);
                        return true;
                    case R.id.navigation_add:
                        Intent intent9=new Intent(MainActivity.this, TryAdd.class);
                        startActivityForResult(intent9, TRY_ADD_RESULT);
                        return true;
                }
                return false;
            }
    
        };
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == TRY_ADD_RESULT) {
                if(resultCode == Activity.RESULT_OK){
                    display_num = data.getIntExtra("result");
                    mSectionsPagerAdapter.notifyDataSetChanged();
                }
            }
        }
    
    
        /**
         * The {@link android.support.v4.view.PagerAdapter} that will provide
         * fragments for each of the sections. We use a
         * {@link FragmentPagerAdapter} derivative, which will keep every
         * loaded fragment in memory. If this becomes too memory intensive, it
         * may be best to switch to a
         * {@link android.support.v4.app.FragmentStatePagerAdapter}.
         */
        private SectionsPagerAdapter mSectionsPagerAdapter;
    
        /**
         * The {@link ViewPager} that will host the section contents.
         */
        private ViewPager mViewPager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            display_num = 3;
    
    
            // Create the adapter that will return a fragment for each of the three
            // primary sections of the activity.
            mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    
            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.container);
            mViewPager.setAdapter(mSectionsPagerAdapter);
    
            TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(mViewPager);
    
            BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
            navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    
    
        }
    
        /**
         * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
         * one of the sections/tabs/pages.
         */
        public class SectionsPagerAdapter extends FragmentPagerAdapter {
    
            public SectionsPagerAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
                switch (position){
    
                    case 0:
                        Novtab tab1 = new Novtab();
                        return tab1;
                    case 1:
                        Hostab tab2 = new Hostab();
                        return tab2;
                    case 2:
                        Idntab tab3 = new Idntab();
                        return tab3;
                    case 3:
                        Fortab tab4 = new Fortab();
                        return tab4;
                    default:
                        return null;
    
    
                }
            }
    
    
    
            @Override
            public int getCount() {
    
                return display_num;
    
            }
    
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "Google";
                    case 1:
                        return "Seznam";
                    case 2:
                        return "Stranka";
                    case 3:
                        return "whatever";
                }
                return null;
            }
        }
    

    活动二:

    public class TryAdd extends AppCompatActivity {
        /**
         * Whether or not the system UI should be auto-hidden after
         * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
         */
        private static final boolean AUTO_HIDE = true;
    
        /**
         * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
         * user interaction before hiding the system UI.
         */
        private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
    
        /**
         * Some older devices needs a small delay between UI widget updates
         * and a change of the status and navigation bar.
         */
        private static final int UI_ANIMATION_DELAY = 300;
        private final Handler mHideHandler = new Handler();
        private View mContentView;
        private final Runnable mHidePart2Runnable = new Runnable() {
            @SuppressLint("InlinedApi")
            @Override
            public void run() {
                // Delayed removal of status and navigation bar
    
                // Note that some of these constants are new as of API 16 (Jelly Bean)
                // and API 19 (KitKat). It is safe to use them, as they are inlined
                // at compile-time and do nothing on earlier devices.
                mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            }
        };
        private View mControlsView;
        private final Runnable mShowPart2Runnable = new Runnable() {
            @Override
            public void run() {
                // Delayed display of UI elements
                ActionBar actionBar = getSupportActionBar();
                if (actionBar != null) {
                    actionBar.show();
                }
                mControlsView.setVisibility(View.VISIBLE);
            }
        };
        private boolean mVisible;
        private final Runnable mHideRunnable = new Runnable() {
            @Override
            public void run() {
                hide();
            }
        };
        /**
         * Touch listener to use for in-layout UI controls to delay hiding the
         * system UI. This is to prevent the jarring behavior of controls going away
         * while interacting with activity UI.
         */
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_try_add);
    
            mVisible = true;
            mControlsView = findViewById(R.id.fullscreen_content_controls);
            mContentView = findViewById(R.id.fullscreen_content);
    
    
            // Set up the user interaction to manually show or hide the system UI.
            mContentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toggle();
                }
            });
    
            // Upon interacting with UI controls, delay any scheduled hide()
            // operations to prevent the jarring behavior of controls going away
            // while interacting with the UI.
    
            ImageView imview3 = (ImageView) findViewById(R.id.imageView3);
            imview3.setClickable(true);
            imview3.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    Intent data = new Intent();
                    data.putExtra("result", 4);
                    setResult(RESULT_OK, data);
                    finish();
                }
            });
    
        }
    
        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
    
            // Trigger the initial hide() shortly after the activity has been
            // created, to briefly hint to the user that UI controls
            // are available.
            delayedHide(100);
        }
    
        private void toggle() {
            if (mVisible) {
                hide();
            } else {
                show();
            }
        }
    
        private void hide() {
            // Hide UI first
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.hide();
            }
            mControlsView.setVisibility(View.GONE);
            mVisible = false;
    
            // Schedule a runnable to remove the status and navigation bar after a delay
            mHideHandler.removeCallbacks(mShowPart2Runnable);
            mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
        }
    
        @SuppressLint("InlinedApi")
        private void show() {
            // Show the system bar
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
            mVisible = true;
    
            // Schedule a runnable to display UI elements after a delay
            mHideHandler.removeCallbacks(mHidePart2Runnable);
            mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
        }
    
        /**
         * Schedules a call to hide() in [delay] milliseconds, canceling any
         * previously scheduled calls.
         */
        private void delayedHide(int delayMillis) {
            mHideHandler.removeCallbacks(mHideRunnable);
            mHideHandler.postDelayed(mHideRunnable, delayMillis);
        }
    }
    

    您必须做一些其他事情来处理实际显示该 Fragment,但我认为交互活动代码更多的是您所要求的...

    【讨论】:

    • 感谢您的建议,我试过了,但我不知道要编写正确的确切代码,我对 android studio 和 java 了解不多,我两周前开始编写应用程序 :D,感谢您的回答,我在上面的问题中添加了代码,如果您还有时间提供帮助,我将不胜感激!
    • 请查看我的编辑并仔细查看更改。公平的警告......我没有对此进行测试,但它应该能让你大部分时间到达那里。希望这可以帮助!如果您仍有问题,请告诉我。
    • 首先非常感谢!我试图将代码添加到这两个类中,但它没有工作,@override 和 TRY_ADD_RESULT 在 onActivityResult 之后的括号中和 get.IntExtra 之后的“result”带有红色下划线(全部在第一个活动中)并且 IMAGE_CLICK_RESULT 是全红色.我尝试了一些 alt-enter 的东西,但没有发现问题。我正在编辑上面的代码以防万一。非常感谢你的帮助!
    • 啊,TRY_ADD_RESULT 和 IMAGE_CLICK_RESULT 错误是我的转录错误。尝试我对 onActivityResult 所做的编辑。我不确定@Override 错误...如果您将鼠标悬停在它上面会说什么吗?
    • 我已经添加了gridview代码,如果它更容易或者通过gridview方式,我也可以将itemclicknavigation设置到dridempty.java并编写你推荐给我的代码..我发现griveiw将为我的应用程序安排得更好..感谢您的回答!
    猜你喜欢
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多