android 如何停止第二标签吐司在第一标签活动中自动显示

7rfyedvj  于 2023-01-19  发布在  Android
关注(0)|答案(3)|浏览(113)

你好我是新蜜蜂到android和我面临的问题标签活动可以任何一个帮助...
我附上了截图
面临的问题-当我打开我的应用程序默认情况下,第一个选项卡显示,但从第二个选项卡“第二个选项卡吐司...“吐司显示在第一个选项卡为什么会发生这种情况?
第1个选项卡为home_fragment. java第2个选项卡vehicle.java,此车辆片段的吐司显示在home片段中,第3个选项卡显示在第2个选项卡片段中

主activity.java

public class MainActivity extends AppCompatActivity {

private static Button button;
private static EditText editText;
private static TextView textView;

 static DatabaseHelper databaseHelper;
/**
 * 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;

private int []tabicon={R.drawable.home,R.drawable.people,R.drawable.messege};

private  TabLayout tabLayout;

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

//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
    // 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);
    setupViewPager(mViewPager);/* new line*/

 //   DatabaseHelper databaseHelper=new DatabaseHelper(getBaseContext(),null,null,1);

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

    tabLayout.setSelectedTabIndicatorHeight(10);

        tabLayout.getTabAt(0).setIcon(R.drawable.home);
        tabLayout.getTabAt(1).setIcon(R.drawable.people);
        tabLayout.getTabAt(2).setIcon(R.drawable.messege);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
        }

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

        }

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

        }
    });

}
private void setupViewPager(ViewPager viewPager)
{
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Home_fragment(),"home");
    adapter.addFragment(new vehicle(),"vehicle");
    adapter.addFragment(new Message(),"Message");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter
{
    private final List<Fragment> mfragmentList=new ArrayList<>();
    private final List<String>mfragmenttitlelist= new ArrayList<>();

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

    @Override
    public Fragment getItem(int position) {
        return mfragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mfragmentList.size();
    }

    public void addFragment(Fragment fragment,String s)
    {
        mfragmentList.add(fragment);
        mfragmenttitlelist.add(s);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mfragmenttitlelist.get(position);
    }
}

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(false);
    builder.setMessage("Do you want to Exit?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //if user pressed "yes", then he is allowed to exit from application
            finish();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //if user select "No", just cancel this dialog and continue with app
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

/**
 * 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) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "home";
            case 1:
                return "vehicle";
            case 2:
                return "Message";
        }
        return null;
    }
}
}

Home_fragment.java

public class Home_fragment extends Fragment
{
private EditText editText;
private Button button;
private TextView textView;

static DatabaseHelper databaseHelper;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //return super.onCreateView(inflater, container, savedInstanceState);

    View view=inflater.inflate(R.layout.fragment_home,container,false);
    editText=(EditText) view.findViewById(R.id.search);
    button=(Button)view.findViewById(R.id.search_btn);
    textView=(TextView)view.findViewById(R.id.search_result);

    databaseHelper=new DatabaseHelper(getContext(),null,null,1);
    databaseHelper.getReadableDatabase();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String string;

            if (editText.getText().toString().isEmpty())
            {
                Toast.makeText(getActivity(), "Please enter bike number", Toast.LENGTH_SHORT).show();
            }
            else {
                try {

                    string = databaseHelper.searchName(editText.getText().toString());

                    textView.setText(string);
                } catch (SQLiteException e)
                {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Please enter name", Toast.LENGTH_SHORT).show();
                }

            }
           // return true;
        }
    });

    return  view;
}
}

vehical.java 第二个片段

public class vehicle extends Fragment
{
private ListView listView;
private TextView textView;
private ArrayAdapter<String> listadapter;

//    DatabaseHelper databaseHelper=new DatabaseHelper(getBaseContext(),null,null,1);
//        databaseHelper.getWritableDatabase();

@Override

public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
    //return super.onCreateView(inflater, container, savedInstanceState);

    View view=inflater.inflate(R.layout.fragment_vehical,container,false);
    listView=(ListView) view.findViewById(R.id.list_view);
    textView=(TextView)view.findViewById(R.id.total_count);

    final DatabaseHelper databaseHelper=new DatabaseHelper(getContext(),null,null,1);
    //databaseHelper.getReadableDatabase();

    final ArrayList<String> arrayList=databaseHelper.readNames();
    final ArrayAdapter<String> arrayAdapter;
    arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_2,android.R.id.text1,arrayList);
    arrayAdapter.notifyDataSetChanged();

    listView.setAdapter(arrayAdapter);

   textView.setText("Total customer  "+String.valueOf(listView.getCount()));
    Toast.makeText(getActivity(), "2nd tab selected", Toast.LENGTH_SHORT).show();


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

            Toast.makeText(getActivity(), "Name selected: "+arrayList.get(position), Toast.LENGTH_SHORT).show();
            //databaseHelper.upDate(arrayList.get(position));
          //  arrayList.get(position)=databaseHelper.upDate(arrayAdapter);

        //    Intent intent=new Intent(getActivity(),Add_customer.class);
          //  startActivity(intent);
            //String name=parent.getSelectedItem();
        }
    });


    FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(),Add_customer.class);
            startActivity(intent);
            Snackbar.make(view, "Customer form", Snackbar.LENGTH_LONG)
                    .setAction("Action", new Add_customer()).show();
        }
    });


    // StringBuffer stringBuffer=databaseHelper.getData();  //get data from database in databasehelper.java

//
//                ArrayList<StringBuffer> cust_list= new ArrayList<>(stringBuffer);
//                cust_list.addAll(Arrays.asList(stringBuffer));
//                listadapter=new ArrayAdapter<String>(vehicle.this,R.layout.fragment_vehical,cust_list);
   return  view;

}
}
e37o9pze

e37o9pze1#

@Override 
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}

您可以在ViewPager适配器内的片段中使用上述方法

if(isVisibleToUser){
 //dosomething when the fragment is visible
}else{
 //dosomething else
}

original post

ffscu2ro

ffscu2ro2#

这是因为当ViewPager完成设置时,即从其适配器添加片段并显示片段时,会调用片段。
因此,如果只有片段可见,则需要执行Toasting
如果您对片段使用支持库,那么您可以使用getUserVisibleHint()或覆盖setUserVisibleHint()来检查片段可见性。
您可以执行以下操作:

public class MyFragment extends Fragment {
  ...
  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
      // Do toasting here.
    } else {
    }
  }
   ...
}

有关ViewPager和Fragment可见性的详细信息,请检查以下内容:How to determine when Fragment becomes visible in ViewPager

4xrmg8kj

4xrmg8kj3#

在开始时添加isVisible,如果用户看不到,则返回

@Override
public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
    //return super.onCreateView(inflater, container, savedInstanceState);
    if(!isVisible) {
        return
    }
    ...
}

相关问题