make the listview receive two texts I'm using fragment - java

Hi guys I have problem.......
I have created fragment activity using viewpager with two tabs,and created listview with two textviews, I want to sent the to texts from tab one to tab two as title and description,I have successfully sent the description but failed to send the title(just I can send only one text) do I need (Getter()/Setter()) ? How to do one??
my fragment_one.java :
public class FragmentOne extends Fragment {
SendMessage SM;
ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_one, container, false);
return rootView;
}
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager)view.findViewById(R.id.viewPager);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
my fragment_two.java :
public class FragmentTwo extends Fragment {
ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getActivity(), R.layout.single_item,R.id.tvdesc, arrayList);
listView.setAdapter(adapter);
}
protected void displayReceivedData(String message) {
arrayList.add(0,message);
adapter.notifyDataSetChanged();
}
}
my custom_items.xml :
<TextView
android:id="#+id/tvtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_toLeftOf="#+id/tvdate"
android:layout_toRightOf="#+id/image"
android:maxLines="1"
android:text="title"
android:textColor="#android:color/black"
android:textSize="15dip"
android:textStyle="bold" />
<TextView
android:id="#+id/tvdesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvtitle"
android:layout_toRightOf="#+id/image"
android:ellipsize="end"
android:maxLines="3"
android:text="desc"
android:textColor="#android:color/black"
android:textSize="13dip"
android:lines="3" />
<TextView
android:id="#+id/tvdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_marginTop="5dip"
android:text="date"
android:textColor="#android:color/black"
android:textSize="12dip" />
note: I have asked this question many times but nobody has helped me, so you would not put any link to another question if you know the answer helped me or ignore this question.

make your SendMessage interface like this
interface SendMessage {
void sendData(String title,String message);
}
Now send both title and message to another fragment using bundle.
I think it will be helpful to you

Related

I could't find IDs of fragment

XML files
Here is the activity_main.xml file. that contains two fragments fragment_list.xml and fragment_deatails.xml
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.udemy.fragmentsapp.ListFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#layout/fragment_list" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fram2"
android:name="com.udemy.fragmentsapp.DetailFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#layout/fragment_detail" />
Here is the fragment_list.xml file. that contain ListView
<ListView
android:id="#+id/lvList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Here is the fragment_details.xml file. that contains one TextView
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:textSize="18dp"
android:textStyle="bold"
android:textColor="#color/black"/>
Java Files
Here is the ListFrag.java file.
ItemSelected activity;
public interface ItemSelected
{
void onItemSelected(int index);
}
public ListFrag() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity = (ItemSelected) context;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ArrayList<String> data = new ArrayList<>();
for (int i = 1; i < 6; i++) {
data.add(i + ". This is item " + i);
}
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,data));
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
super.onListItemClick(l, v, position, id);
activity.onItemSelected(position);
}
Here is the DeatailFrag.java file.
public DetailFrag(){
super(R.layout.fragment_detail);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
Here is the MainActivity.java file. when I want to access the ID "tvDescription" then it's showing ERROR: #layout/activity_main does not contain a declaration with id tvDescription.
Please help me. How can I access the ID? Tell me which one is the way to find IDs.
TextView tvDescription;
ArrayList<String> description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDescription = findViewById(R.id.tvDescription);
for (int i = 1; i < 6; i++) {
description.add("Description for item " + i);
}
}
#Override
public void onItemSelected(int index) {
tvDescription.setText(description.get(index));
}
Please run this code in your IDE.
The problem is that your activity and fragment are different classes. And although it is obvious that they represent a single view tree, in fact, in each component class, you should refer to the elements of only its layout.
Thus you need to use
TextView tvDescription = findViewById(R.id.tvDescription);
Directly in the DeatailFrag.onViewCreated after super.onViewCreated
And then, somehow pass the received value back to the activity, if necessary
Happy learning

Android studio null object reference error while changing component visibility

I'm making an app that displays the same menus for different users, each menu being a fragment, but depending on the user certain things are visible and others aren't.
However, when I try to set a component's visibility as GONE I get a null pointer exception error, I'm still testing so I'm only using a textView on the fragment xml.
I've already tried initializing both the TextView and the FragmentMenuEncomenda, the class of the fragment I'm using, objects, both inside the if clause before the onCreate() method, and after the setContentView(), like the tabLayout and viewPager.
The if clause was only to make sure the user type was correct and the code in question is as follows:
public class PaginaInicialCliente extends AppCompatActivity {
private SharedPreferences sharedpreferences;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagina_inicial_cliente);
tabLayout = findViewById(R.id.tabLayoutCliente);
viewPager = findViewById(R.id.viewPagerCliente);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//fragments a adicionar
adapter.addFragment(new FragmentMenuEncomendas(), "Encomendas");
adapter.addFragment(new FragmentMenuOpcoes(), "Opções");
//inicializar o tab layout
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
if (sharedpreferences.getInt("tipo",0)==3) {
Log.d("USER_DEBUG","Cliente");
FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
//THE ERROR IS HERE
fragmentMenuEncomendas.getActivity().findViewById(R.id.textViewEncomendas).setVisibility(View.GONE);
}
}
}
The FragmentMenuEncomenda class:
public class FragmentMenuEncomendas extends Fragment {
View v;
public FragmentMenuEncomendas(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.encomendas_fragment, container, false);
return v;
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textViewEncomendas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
All the answers I've searched didn't work, I don't know if it's because I'm trying to change the visibility inside the on create method.
Because view is not created when you call the function.
public class FragmentMenuEmpresas extends Fragment {
View v;
View textView;
boolean isTextViewShow = false;
boolean isViewCreated = false;
public FragmentMenuEmpresas() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.empresas_fragment, container, false);
textView = v.findViewById(R.id.textViewEncomendas);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (isTextViewShow) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.GONE);
}
isViewCreated = true;
}
void setIsTextViewShow() {
if (isViewCreated) {
textView.setVisibility(View.VISIBLE);
} else {
isTextViewShow = true;
}
}
void setIsTextViewGone() {
if (isViewCreated) {
textView.setVisibility(View.GONE);
} else {
isTextViewShow = false;
}
}
}
then you can call the setIsTextViewShow or setIsTextViewGone anytime you want
FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
fragmentMenuEncomendas.setIsTextViewShow();//show
fragmentMenuEncomendas.setIsTextViewGone();//gone

RecyclerView No adapter attached; skipping layout, Data not showing

I'm making a music player application where I'm using a loader to load song data to the adapter which is to be shown using a RecyclerView. However, I'm getting this weird error of my adapter methods not working. Only the constructor method of adapter is getting called.
I'm also getting "No adapter attached; skipping layout" despite going through all the available solutions here in stack overflow.
Few points to be noted:
I've tried all the solutions for "No adapter attached; skipping layout" in
recyclerview No adapter attached; skipping layout thread and all associated duplicate threads.
The RecyclerView I'm using is not the regular one but FastScrollRecyclerView, but since it extends from the regular RecyclerView and there are no relatable issues mentioned on github so I'm convinced that using this library is not an issue here
I've also tried all solutions for the adapter methods not being called from this thread but no luck.
Here's the code:
SongsFragment.java
public class SongsFragment extends Fragment
implements LoaderManager.LoaderCallbacks<List<Song>>{
public static final String LOG_TAG = SongsFragment.class.getSimpleName();
private static final int LOADER_ID = 1;
private ContentResolver mContentResolver;
private SongListAdapter mSongListAdapter;
private List<Song> mSongs;
#BindView(R.id.rvSongs) FastScrollRecyclerView mRecyclerView;
public SongsFragment() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(getActivity());
mSongs = new ArrayList<>();
mRecyclerView = new FastScrollRecyclerView(getContext());
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mSongListAdapter = new SongListAdapter(getContext(), mSongs);
mRecyclerView.setAdapter(mSongListAdapter);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(LOADER_ID, null, this).forceLoad();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_songs, container, false);
}
#Override
public Loader<List<Song>> onCreateLoader(int id, Bundle args) {
mContentResolver = getActivity().getContentResolver();
return new SongsLoader(getContext(), mContentResolver);
}
#Override
public void onLoadFinished(Loader<List<Song>> loader, List<Song> data) {
mSongs = data;
mSongListAdapter.setData(mSongs);
}
#Override
public void onLoaderReset(Loader<List<Song>> loader) {
mSongListAdapter.setData(new ArrayList<Song>());
}
}
SongsListAdapter.java
public class SongListAdapter
extends FastScrollRecyclerView.Adapter<SongListAdapter.SongItemViewHolder>
implements FastScrollRecyclerView.SectionedAdapter{
public static final String LOG_TAG = SongListAdapter.class.getSimpleName();
private Context mContext;
private List<Song> mSongList = new ArrayList<>();
public SongListAdapter(Context context, List<Song> songList) {
Log.d(LOG_TAG, "Constructor called");
mContext = context;
mSongList = songList;
}
#NonNull
#Override
public String getSectionName(int position) {
return String.valueOf(mSongList.get(position).getTitle().charAt(0)).toUpperCase();
}
#Override
public SongItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(LOG_TAG, "onCreateViewHolder called");
View view = LayoutInflater.from(mContext).inflate(R.layout.list_item_song, null);
return new SongItemViewHolder(view);
}
#Override
public void onBindViewHolder(SongItemViewHolder holder, int position) {
Log.d(LOG_TAG, "onBindViewHolder called");
Uri albumArtUri = mSongList.get(position).getAlbumArtUri();
Glide.with(mContext)
.load(albumArtUri)
.into(holder.albumArt);
holder.titleText.setText(mSongList.get(position).getTitle());
holder.artistText.setText(mSongList.get(position).getArtistName());
Log.d("Data", albumArtUri.toString() + "\n" + mSongList.get(position).getTitle() + "\n" + mSongList.get(position).getArtistName());
}
#Override
public int getItemCount() {
Log.d(LOG_TAG, "getItemCount called");
return (mSongList != null ? mSongList.size() : 0);
}
public void setData(List<Song> songs){
mSongList = songs;
notifyDataSetChanged();
}
public class SongItemViewHolder extends FastScrollRecyclerView.ViewHolder {
ImageView albumArt;
TextView titleText;
TextView artistText;
SongItemViewHolder(View view) {
super(view);
Log.d(LOG_TAG, "SongItemViewHolder called");
albumArt = (ImageView) view.findViewById(R.id.item_song_image);
titleText = (TextView) view.findViewById(R.id.item_song_title);
artistText = (TextView) view.findViewById(R.id.item_song_artist_name);
}
}
}
fragment_songs.xml (SongsFragment is inflating this layout)
<?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:layout_width="match_parent"
android:layout_height="match_parent">
<com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
android:id="#+id/rvSongs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fastScrollPopupBgColor="#color/colorAccent"
app:fastScrollPopupTextColor="#android:color/primary_text_dark"
app:fastScrollThumbColor="#color/colorAccent"/>
</ScrollView>
list_item_song.xml (Individual item in recycler view)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_gravity="center_horizontal"
android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:background="#FFFFFF"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingStart="8dp"
android:paddingTop="10dp">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/item_song_image"
android:layout_width="64dp"
android:src="#drawable/music_placeholder"
android:layout_height="64dp"/>
</FrameLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/item_song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Song_Title"/>
<TextView
android:id="#+id/item_song_artist_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:textSize="12sp"
android:text="Song_Artist"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
This has been really frustrating. Please review the code and help me with this. I think I've done everything correctly but I may be wrong. I know scrollview and recyclerview don't go that well but I've seen the preview and the recycler view shows. Any help will be appreciated. Thanks!
Try setting adapter in onLoadFinished() and also use getActivity() for context in adapter object
#Override
public void onLoadFinished(Loader<List<Song>> loader, List<Song> data) {
mSongs = data;
mSongListAdapter = new SongListAdapter(getActivity(), mSongs);
mRecyclerView.setAdapter(mSongListAdapter);
}
also in this
mRecyclerView = new FastScrollRecyclerView(getContext()); to
mRecyclerView = new FastScrollRecyclerView(getActivity());
Basically use getActivity() for context in fragment class
Ugh! I wasted a lot of time in this but finally came out with the solution. I removed Butterknife binding and used conventional findViewById inside onCreateView() of SongsFragment after capturing the view instance by changing the onCreateView() to this:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_songs, container, false);
mRecyclerView = (FastScrollRecyclerView) rootView.findViewById(R.id.rvSongs);
//Rest of the things
}
Turns out I was using ButterKnife the wrong way so the instance mRecyclerView was null but later with line
mRecyclerView = new FastScrollRecyclerView(getContext()); it wasn't null anymore but it still wasn't connected to the view so I didn't get NullPointerException and the code didn't work.
I know it was a noob mistake :D
Correct way to use ButterKnife with fragments as picked up from official website is:
public class FancyFragment extends Fragment {
#BindView(R.id.button1) Button button1;
#BindView(R.id.button2) Button button2;
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fancy_fragment, container, false);
ButterKnife.bind(this, view);
// TODO Use fields...
return view;
}
}

Add a clickable button on Fragment layer in the center of the screen

I want to add button on fragment layer in the middle of the screen , button added but it is not clicking & goes to the desired activity. this is my code of java & xml:-
xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/a6">
<Button
android:id="#+id/hardware"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="213dp"
android:background="#android:color/darker_gray"
android:text="Button" />
</RelativeLayout>
Java code
public class SwapFragmentsix extends Fragment {
Button hardware;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_swap_fragmentsix, container, false);
hardware = (Button) view.findViewById(R.id.hardware);
hardware.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HardwareKeyPoints.class);
startActivity(intent);
}
});
return inflater.inflate(R.layout.activity_swap_fragmentsix, container, false);
}
}
You should try this
public class SwapFragmentsix extends Fragment {
Button hardware;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_swap_fragmentsix, container, false);
hardware = (Button) view.findViewById(R.id.hardware);
hardware.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HardwareKeyPoints.class);
startActivity(intent);
}
});
return view; //change to this
}
}
It is because of you are returning
inflater.inflate(R.layout.activity_swap_fragmentsix,
container,false); instead of view. That is you are inflating the view again.

How to navigate between fragments?

I am new to Android Fragments. I have 2 different fragments and want to navigate from one fragment to another using buttons. For example, in fragmentA when i press a button, i go to fragmentB and vise verse.
Here are my simple codes:
FragmentA.java
public class FragmentA extends Fragment {
public FragmentA(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
return rootView;
}
}
fragmenta.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="670dp"
android:gravity="top"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:text="Fragment 1"
android:textStyle="bold"
android:textSize="22dp" />
</LinearLayout>
FragmentB.java
public class FragmentB extends Fragment {
public FragmentB(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_b, container, false);
return rootView;
}
}
fragmentb.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="670dp"
android:gravity="top"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:text="Fragment 2"
android:textStyle="bold"
android:textSize="22dp" />
</LinearLayout>
I need codes (both java and xml) for buttons. Help from scratch would be appreciated. Thanks in advance!!
Check This Tutorial and Below Code for refrence
Fragment1.java
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
public void onClick(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
Code in Activity
public class MyActivity extends FragmentActivity implements OnListenerChangeFragment {
FragmentA mFragmentA;
FragmentB mFragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onShowFragmenA() {
//replace mFragmentB by mFragmentA
}
#Override
public void onShowFragmenB() {
//replace mFragmentA by mFragmentA
}
}
//Code in Fragments
public class FragmentA extends Fragment {
private OnListenerChangeFragment mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Button mButton = new Button(getActivity());
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onShowFragmenB();
}
});
return mButton;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnListenerChangeFragment) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ " must implement OnListenerChangeFragment");
}
}
}
public class FragmentB extends Fragment {
private OnListenerChangeFragment mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Button mButton = new Button(getActivity());
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onShowFragmenA();
}
});
return mButton;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnListenerChangeFragment) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ " must implement OnListenerChangeFragment");
}
}
}

Categories

Resources