Can't Open Fragment when clicked button - java

I have created 2 fragment and their layout,
when i click button on profile fragment it should open flat layout, but
it force stop application and its not opening the second fragment,
i have included fragment code and its layout code..
profilefragment.java
public class ProfileFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.button, new flatview(), "NewFragmentTag");
ft.commit();
}
profile.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}"
android:id="#+id/semester">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
flatview.java
public class flatview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.flat, container, false);
}
flat.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="second fragement"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
logcat
06-19 07:57:56.945 26457-26457/com.idealdeveloper.saltechnical E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.idealdeveloper.saltechnical, PID: 26457
java.lang.ClassCastException: android.widget.Button cannot be cast to android.view.ViewGroup
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Try this I guess it will work for you
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}"
android:id="#+id/semester">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/fragmentLayout"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Class
public class ProfileFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragmentLayout, new flatview(), "NewFragmentTag");
ft.commit();
}
I hope this one will helps you

The fragment transaction inserts a View into a ViewGroup, so you can't just replace a Button. You could just replace the parent semester, since it is a ViewGroup.
public void onButtonClicked(View view) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.semester, new flatview(), "NewFragmentTag");
ft.commit();
}
If your intention is also to remove the button, you will need to do it manually since the FragmentManager can only modify runtime transactions:
ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.semester);
parent.removeView(view);

You have to provide a ViewGroup root for the flat.xml layout , for example you can surround the TextView with a LinearLayout
flat.xml :
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="second fragement"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
</LinearLayout>

Related

Why doesn't my ImageView as a button work?

I'm trying to make an ImageView button inside a fragment to open another fragment in a navigation drawer but I have encountered a problem where I can't set an OnCliCkListener to my ImageView button. I tried searching fixes on youtube but I can't seem to find a fix to my problem.
Here's the error
Here's the error as text
HomeFragment.java
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(getLayoutInflater());
return binding.getRoot();
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
binding.IVOrdersButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment OrdersFragment = new OrdersFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_dashboard, OrdersFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
public void onDestroy(){
super.onDestroy();
binding = null;
}
}
Dashboard_fragment.xml
<TextView
android:id="#+id/DashboardTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Dashboard"
android:textColor="#000000"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
<ImageView
android:id="#+id/IVOrdersButton"
android:layout_width="76dp"
android:layout_height="89dp"
android:clickable="true"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/DashboardTV"
app:layout_constraintVertical_bias="0.074"
app:srcCompat="#drawable/ic_orders"
tools:srcCompat="#drawable/ic_orders" />
<TextView
android:id="#+id/OrdersLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ordersDashboard"
android:textColor="#000000"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.187"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/IVOrdersButton"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
You're inflating FragmentHomeBinding based on fragment_home.xml but the layout with the imageview is called Dashboard_fragment.xml. Move the ImageView to fragment_home.xml to be able to use it this way.
Check the code again, it is missing #Override before the onCreateView and onViewCreated functions

Dynamically want to update the text in edit Text from admin end and should reflect updated text in user end

I have created 3 fragments for one of my project ..this is one of them. So basically I want When ever the admin(aAccountFragment) will click on the update quote button the quote should be updated and should be reflected in AccountFragment.xml file in the user end.
For this in the admin(aAccountFragment) side I have provided and edit text where the admin can update the quote every 24hrs.and in the user end(AccountFragment) the user can only see the updated quote when ever the admin will update the quote because at user end textview is provided and in the admin end EditText is provided.
For this I have attached my aAccountFragment.xml, AccountFragment.xml,AccountFragment.java,aAccountFragment.java code.
This is my aAccountFragment.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".aAccountFragment"
android:background="#drawable/ic_launcher_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="339dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="465dp"
android:text=" QUOTE OF THE DAY"
android:textColor="#color/black"
android:textSize="30sp" />
<EditText
android:layout_width="323dp"
android:layout_height="111dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="21dp"
android:layout_marginBottom="273dp"
android:text="-She decided to start living the life she imagined-"
android:textColor="#color/DarkRed"
android:textSize="25sp" />
<Button
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="107dp"
android:layout_marginBottom="177dp"
android:background="#color/LightBlue"
android:text="UPDATE QUOTE"
android:textColor="#color/black"
android:textSize="20sp" />
<Button
android:id="#+id/logout1"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="43dp"
android:layout_marginBottom="75dp"
android:background="#color/Pink"
android:text="LOG OUT"
android:textColor="#color/black"
android:textSize="20sp" />
</RelativeLayout>
this is my aAccountFragment.java code.
public class aAccountFragment extends Fragment {
Button logout1;
public aAccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.afragment_account, container, false);
logout1 = view.findViewById(R.id.logout1);
logout1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), aloginpage.class));
Toast.makeText(getActivity().getApplicationContext(), "SUCCESSFULLY LOGOUT", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
this is my AccountFragment.xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AccountFragment"
android:background="#drawable/ic_launcher_background">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="339dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="41dp"
android:layout_marginBottom="465dp"
android:text=" QUOTE OF THE DAY"
android:textColor="#color/black"
android:textSize="30sp" />
<TextView
android:layout_width="296dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="49dp"
android:layout_marginBottom="272dp"
android:text="-She decided to start living
the life she imagined-"
android:textColor="#color/DarkRed"
android:textSize="25sp" />
<Button
android:id="#+id/logout"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="28dp"
android:layout_marginBottom="75dp"
android:background="#color/Pink"
android:text="LOG OUT"
android:textColor="#color/black"
android:textSize="20sp" />
</RelativeLayout>
this is my AccountFragment.java code.
public class AccountFragment extends Fragment {
Button logout;
public AccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_account, container, false);
logout = view.findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), loginpage.class));
Toast.makeText(getActivity().getApplicationContext(), "SUCCESSFULLY LOGOUT", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
STEP-1: To take quote input from edittext inside AdminFragment.java. I am not posting it's xml file as nothing important there except an EditText. You can put it inside any Activity.
AdminFragment.java
public class AdminFragment extends Fragment {
public static AdminFragment newInstance() {
return new AdminFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
EditText quoteEditText = view.findViewById(R.id.quote_et);
Button quoteBtn = view.findViewById(R.id.quote_btn);
quoteBtn.setOnClickListener(v -> {
String quote = quoteEditText.getText().toString();
if (quote.isEmpty()){
Toast.makeText(getContext(),"Please Enter Quote!",Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(getActivity(), BottomNavigationActivity.class);
intent.putExtra("quote",quote);
startActivity(intent);
}
});
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
STEP-2:
As you would have declared BottomNavigationActivity which would have 3 fragments namely SnapFragment.java , HomeFragment.java and AccountFragment.java. Quote text will be received from AdminFragment.java while click on updateQuote button inside BottomNavigationActivity. Once quote is received inside BottomNavigationActivity, I am opening 3rd Fragment i.e AccountFragment to show quoted text.
BottomNavigationActivity.java
public class BottomNavigationActivity extends AppCompatActivity {
String updatedQuote = "";
BottomNavigationViewModel bottomNavigationViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
bottomNavigationViewModel = new ViewModelProvider(this).get(BottomNavigationViewModel.class);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_snap, R.id.navigation_home, R.id.navigation_account)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
updatedQuote = getIntent().getStringExtra("quote");
Log.d("tisha==>>","Quote = "+updatedQuote);
bottomNavigationViewModel.setQuoteLiveData(updatedQuote);
// Below I am selecting 3rd Fragment to show Quote
navView.setSelectedItemId(R.id.navigation_account);
}
}
activity_bottom_navigation.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am using ViewModel here, because it will be easier to pass quote data from current activity to AccountFragment.java as AccountFragment is not instantiated by it's constructor here. BottomNavigationViewModel is responsible for storing quote and provide wherever it is required.
BottomNavigationViewModel.java
public class BottomNavigationViewModel extends ViewModel {
private final MutableLiveData<String> quoteLiveData;
public String getQuoteLiveData(){
return quoteLiveData.getValue();
}
public void setQuoteLiveData(String quote){
quoteLiveData.setValue(quote);
}
public BottomNavigationViewModel(){
quoteLiveData = new MutableLiveData<>();
}
}
STEP-3:
Now inside AccountFragment, I just get the view model which is created inside BottomNavigationActivity and collecting quote from that and displaying it in TextView.
AccountFragment.java
public class AccountFragment extends Fragment {
private String mQuote;
private BottomNavigationViewModel bottomNavigationViewModel;
public AccountFragment() {
// Required empty public constructor
}
public static AccountFragment newInstance(String quote) {
return new AccountFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bottomNavigationViewModel = new ViewModelProvider(requireActivity()).get(BottomNavigationViewModel.class);
mQuote = bottomNavigationViewModel.getQuoteLiveData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
TextView quoteView = view.findViewById(R.id.quote_tv);
quoteView.setText(mQuote);
}
}

Error on inflating a fragment

I have a fragment and I am inflating it like below, but it is giving runtime error:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View jobsView = inflater.inflate(R.layout.fragment_job_information, container, false);
textView = (TextView) jobsView.findViewById(R.id.textView);
if (jobInfo == null) {
EmployerHistory jobsQuery=new EmployerHistory();
jobInfo = jobsQuery.getJobInfo(employerName, position);
}
textView.setText(jobInfo.get("jobName").toString());
return jobsView;
}
Its corresponding layout is:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/jobInfoFragment">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ankit.job_depot.employer.view.JobInformation">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</fragment>
Actually I am already on a fragment with listview and when user clicks on an element of listview that fragment needs to get changed by a new fragment, in my new fragment I have:
l
istViewJobHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobInformation newFragment = new JobInformation();
android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.listViewJobHistory, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
I am getting the following exception:
07-28 18:49:39.681 14474-14474/com.example.ankit.job_depot
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ankit.job_depot, PID: 14474
android.view.InflateException: Binary XML file line #1: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.example.ankit.job_depot.employer.view.JobInformation.onCreateView(JobInformation.java:45)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
I think your main Activity should extend FragmentActivity
import android.support.v4.app.FragmentActivity;

Access textfield of nested fragment

I have several fragments. Some fragments have the same buttons at the top and the bottom of the fragment, but the content is different.
Therefore I'm using nested fragments for the top and the buttom part. This is my java class: LogFragment.java. I insert two fragments for the top navigation and the footer at the bottom.
public class LogFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.fragment_log, container, false);
Fragment navigationFrag = new NavigationFrag();
FragmentTransaction trans1 = getChildFragmentManager().beginTransaction();
trans1.add(R.id.navigationFrag, navigationFrag).commit();
Fragment footerFragment = new FooterFragment();
FragmentTransaction trans2 = getChildFragmentManager().beginTransaction();
trans2.add(R.id.footerFragment, footerFragment).commit();
return rootview;
}
}
This is the layout file: fragment_log.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout android:id="#+id/NavigationFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:layout_below="#+id/button1"/>
</RelativeLayout>
<FrameLayout android:id="#+id/FooterFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
The nested NavigationFragment and FooterFragment contains some buttons, images or textfields. For example: fragment_footer.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/logInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LOG" />
</RelativeLayout>
My question:
How can I access/manipulate/fill in some data of the elements in my nested fragments by the LogFragment.java class?
For example:
I want to access the textview with the id logInfo of the nested fragment_footer.xmlby the LogFragment.java.
Just use [child fragment].getView().findViewById(R.id.[elemnet id]) to get the elements in nested fragments. For example :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.fragment_log, container, false);
Fragment navigationFrag = new NavigationFrag();
FragmentTransaction trans1 = getChildFragmentManager().beginTransaction();
trans1.add(R.id.navigationFrag, navigationFrag).commit();
final Fragment footerFragment = new FooterFragment();
FragmentTransaction trans2 = getChildFragmentManager().beginTransaction();
trans2.add(R.id.footerFragment, footerFragment).commit();
Button btn1 = (Button)rootview.findViewById(R.id.button1);
btn1.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v) {
TextView txv = (TextView)footerFragment.getView().findViewById(R.id.logInfo);
txv.setText("Updated log of Footer");
}
});
return rootview;
}
By the way,
the child fragment is available to access only after onCreateView(),
so you need to declare the child fragment as final or member data of parent.

How to identify a fragment from it's button's xml onClick view?

I have some fragments that are being added programatically with differing tags. Each holds a button with an xml onClick that gets passed a view. How do I identify which fragment was clicked from that view? Code is below.
NewFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_fragment, container, false);
TextView tv = (TextView) view.findViewById(R.id.name);
Bundle bundle = this.getArguments();
int index = bundle.getInt("index");
tv.setText(Integer.toString(index));
return view;
}
Activity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
for (int loop = 0; loop < 4; loop++) {
NewFragment fragment = new NewFragment();
Bundle args = new Bundle();
args.putInt("index", loop);
fragment.setArguments(args);
//tag set to value of loop here
ft.add(R.id.new_fragment, fragment, Integer.toString(loop));
}
ft.commit();
}
public void toggleEdit(View view) {
//How do I find clicked fragment?
}
new_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/test">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="5dp"
android:padding="5dp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="Test"
/>
</LinearLayout>
<!-- Button in question is below -->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/edit"
android:onClick="toggleEdit"
android:id="#+id/edit_button"
/>
</LinearLayout>
Have your Fragment define an interface which your activity implements. Give that interface a method with a string parameter, and onClick, pass in the current Fragment's tag.
See this guide on Fragment communication for more detail http://developer.android.com/training/basics/fragments/communicating.html

Categories

Resources