add button inside viewpager fragment and intent in another activity? - java

I'm trying to create an app which will display my menu and I use viewpager fragment for display and I want to add a button for every page of the viewpager which will intent to another activity can someone help me for this?
This is my viewpager:
public class menu_meat_viewer extends FragmentActivity{
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meat_viewer);
initialisePaging();
}
private void initialisePaging(){
List<Fragment> fragments=new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, meat_adobo.class.getName()));
fragments.add(Fragment.instantiate(this, meat_bbqpork.class.getName()));
fragments.add(Fragment.instantiate(this, meat_tlshrmp.class.getName()));
mPagerAdapter=new menu_meat_viewer_adapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager) findViewById(R.id.meat_view);
pager.setAdapter(mPagerAdapter);
}
}
and this is one of my page in view pager:
public class meat_adobo extends Fragment{
int price= 70;
String name="classic chicken adobo";
MDB mdb;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(container==null){
return null;
}
return(RelativeLayout) inflater.inflate(R.layout.meat_adobo,container,false);
}
}

Create a button in your fragment layout
and
Add this code to your fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.meat_adobo, container, false);
Button b=(Button) v.findViewById(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent in=new Intent(getActivity(),SecondActivity.class);
startActivity(in);
}
});
return v;
}
and add import android.view.View.OnClickListener;

Related

Empty fragment after returning from the Second fragment. (Android App, Java)

I just created my first Android app through Android Studio using Java. I am working with two fragments in the process. The first fragment consists of a gridview with cards. When you click on a card you get to the Second Fragment. So far everything works. My problem is that when returning from the Second Fragment to the First Fragment (CategoryFragment) via the AppBar, the content remains empty. It seems that the method onCreateView is not executed again. What did I do wrong? Did I not understand something correctly?
public class CategoryFragment extends Fragment implements CardViewAdapter.ItemClickListener{
private RecyclerView recyclerView;
private CategoriesService categoriesData;
private SharedPreferences sharedPreferences;
private RequestQueue queue;
private FragmentCategoryBinding binding;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = this.getActivity().getSharedPreferences("SPOTIFY", 0);
queue = Volley.newRequestQueue(this.getActivity());
Toast.makeText(this.getContext(), "categoryFragment loaded" ,Toast.LENGTH_LONG).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_category, container, false);
categoriesData = new CategoriesService( view.getContext(), this.queue, this.sharedPreferences);
categoriesData.loadData();
CardViewAdapter mAdapter = new CardViewAdapter(view.getContext(), categoriesData.getCategories());
mAdapter.setClickListener(this);
recyclerView = view.findViewById(R.id.categoriesGrid);
recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(), 6));
recyclerView.setAdapter(mAdapter);
return view;
/*
binding = FragmentCategoryBinding.inflate(inflater, container, false);
return binding.getRoot();
*/
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*
binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(CategoryFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
*/
}
#Override
public void onItemClick(View view, int pos) {
SpotifyCategoryCard item = categoriesData.getCategory(pos);
Toast.makeText(getContext(), "Click on '"+ item.getTitle() +"' (Type: '"+item.type+"')" ,Toast.LENGTH_SHORT).show();
NavHostFragment.findNavController(CategoryFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}

First Click in button does not get the text in the EditText object

The problem is that when i click in the button the first time no text is in the EditText object, in the second click it works but does not replace the frame.
I Have one activity with a container for a fragment that has a editText and a button, when click the button i replace the fragment in the container with another fragment to display the text in the edit text.
I'm following this tutorial:
https://www.youtube.com/watch?v=OLbsiE42JvE&list=PLshdtb5UWjSrOJfpFOE-u55s3SnY2EO9v&index=14
i'm in video "Android tutorial (2018) - 14 - Fragment to Fragment Communication".
The diference from this tutorial from my app is that my activity is the third in the same project, and i'm working in that activity as it was my main.
public class FinalActivity extends AppCompatActivity implements HeadLineFragment.OnMessageListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final);
if(findViewById(R.id.final_activity_fragment)!= null) {
if (savedInstanceState != null) {
return;
}
HeadLineFragment headLineFragment = new HeadLineFragment();
getSupportFragmentManager().beginTransaction().add(R.id.final_activity_fragment, headLineFragment, null).commit();
}
}
#Override
public void onMessageSend(String message) {
ArticleFragment articleFragment = new ArticleFragment();
Bundle bundle = new Bundle();
bundle.putString("message",message);
articleFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.final_activity_fragment, articleFragment,null).addToBackStack(null).commit();
}
}
public class HeadLineFragment extends Fragment {
OnMessageListener onMessageListener;
private Button button;
private EditText editText;
public interface OnMessageListener{
public void onMessageSend(String message);
}
public HeadLineFragment(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.headline_fragment, container, false);
button = view.findViewById(R.id.bfrag);
editText = view.findViewById(R.id.editText21);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String message = editText.getText().toString();
String s = editText.getText().toString();
onMessageListener.onMessageSend(message);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = (Activity) context;
try {
onMessageListener = (OnMessageListener) activity;
}catch (ClassCastException e){
throw new ClassCastException(activity.toString() + " must implement OnMessageListener....");
}
}
#Override
public void onResume() {
super.onResume();
editText.setText("");
}
}
public class ArticleFragment extends Fragment {
private TextView textView;
public ArticleFragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(
R.layout.article_fragment,container, false);
textView = view.findViewById(R.id.txt_message_display);
Bundle bundle = getArguments();
String message = bundle.getString("message");
textView.setText(message);
return view;
}
}
I expect that the functionality has the same behavior as in the video of the tutorial
I eventually solved my own problem, the layout of the Activity had a fragment instead of a frame layout. By changing that the problem was solved.

childfragment does not work when i click the button

I am trying to create a memory game, at the first page when I click on the play button it shows the categories and I used fragments. When I click on a button to go to another fragment it doesn't work.
Mainactivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageViewA = findViewById(R.id.play_title);
imageViewA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
FragmentPlay fragA = new FragmentPlay();
transaction.add(R.id.fragmentContainer_main, fragA);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
}
FragmentPlay.java
public class FragmentPlay extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_play,container,false);
return rootView;
}
public void addFragB(){
FragmentManager childFragMan=getChildFragmentManager();
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
FragmentAnimal fragmentAnimal = new FragmentAnimal();
childFragTrans.add(R.id.fragmentContainer_main2, fragmentAnimal);
childFragTrans.addToBackStack(null);
childFragTrans.commit();
}
}
FragmentAnimal.java
public class FragmentAnimal extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_animal,container,false);
return rootView;
}
}

Where should I put my code when using a tabbed activity?

I am having a rather annoying problem using tabs in android. I am not sure how they work, problem I am having is knowing where to put the logic of my code. say for example on the first tab I wanted to apply a calendar and the second tab upload a file, for example where would I put this logic, I have 3 xml fragments and so far I have been trying to code the logic by the onCreateView. If anyone could explain how tabbed activities work I would be eternally grateful I used the default android set up for a tabbed activity and added 3 fragments.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_message, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2){
View rootView = inflater.inflate(R.layout.fragment_read, container, false);
TextView textView= (TextView)rootView.findViewById(R.id.textView_two);
textView.setText("Working");
return rootView;
}
else{
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
// would I put my logic here?
return rootView;
}
}
}
Update 2
So now I am trying to listen for button presses and show a toast on one of the fragments,the button does not respond and the Toasts do not appear.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView=inflater.inflate(R.layout.fragment_calendar, container, false);
//final ActionBar actionBar = getSupportActionBar();
//actionBar.setDisplayHomeAsUpEnabled(false);
//actionBar.setTitle(null);
//Toast.makeText(getActivity(),"AKHBKH",Toast.LENGTH_LONG).show();
Button button1=(Button)rootView.findViewById(R.id.button_test1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("","");
Toast.makeText(getActivity(),"ddfdf",Toast.LENGTH_LONG).show();
}
});
PS I have tried all these on the Toast
getActivity()
getActivity().getApplicationContext()
getBaseContext()
getContext()
You can take three fragments and All the logic you want to implement should be in each of the fragment respectively. Take MainActivity to View all the fragments. Here i'll share my piece of code.
MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Admin(), "ADMIN");
adapter.addFragment(new Faculty(), "FACULTY");
adapter.addFragment(new Student(), "STUDENT");
viewPager.setAdapter(adapter);
}
//----------------------------------------------------------------------------------------------
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed(){
//Do Here what ever you want do on back press;
}
}
I'll share the code of any one of the fragments: Admin
public class Admin extends Fragment {
EditText aid;
EditText apassword;
Button submit1,changepass;
String id = null, pass = null;
String table = null;
public Admin() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView=inflater.inflate(R.layout.fragment_admin, container, false);
aid=(EditText)rootView.findViewById(R.id.admin_id);
apassword=(EditText)rootView.findViewById(R.id.admin_password);
changepass=(Button)rootView.findViewById(R.id.changePass);
submit1=(Button)rootView.findViewById(R.id.submit1);
submit1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submit1();
}
});
changepass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in=new Intent(getActivity(),ChangePassword.class);
startActivity(in);
}
});
// Inflate the layout for this fragment
return rootView;
}
//For Admin login Authentication
public void submit1() {
id = aid.getText().toString();
pass = apassword.getText().toString();
Log.d("id", id);
Log.d("pass", pass);
table="admin";
// new ExecuteTask().execute(id, pass, table);
}}
Initially create an activity MainActivity.
You must create 3 fragments.Extend your activity from FragmentActivity and also implement ActionBar.TabListener
Refer this tutorial:
http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

Add fragment into viewPager's fragment

I have viewpager with 3 fragments (same layout - some EditText and Buttons) and I want to dynamically add small fragment above the viewpager fragment, write something in and then hide it.
This is what I tried:
MainActivity.java:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return MainFragment.newInstance("1");
case 1: return MainFragment.newInstance("2");
case 2: return MainFragment.newInstance("3");
default: return MainFragment.newInstance("");
}
}
#Override
public int getCount() {
return 3;
}
}
}
MainFragment.java:
public class MainFragment extends android.support.v4.app.Fragment {
EditText contentEdit;
String content, ID;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ID = getArguments().getString("msg");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
contentEdit = (EditText) view.findViewById(R.id.editText);
contentEdit.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
public void onSwipeBottom() {
final ViewGroup newView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.fragment_title, container, false);
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
container.removeView(newView);
}
});
container.addView(newView, 0);
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
return view;
}
}
Try to put a frame layout above that viewPager layout BUT set it's visibility to GONE therefore it won't "exist". Now in your pager onItemClick listener for that small fragment you want to show call findViewByID(R.id.YourFrameLayout).setVisibility(View.VISIBLE); and when you want to hide it, well you get the idea. Don't forget to add your fragment to that container, e.g. YourFrameLayout

Categories