Change Fragment's TextViews's text from Activity - android

I want to change an textView's text via an Activity, but when I change by this code:
public class MainActivity extends AppCompatActivity {
private TextView txtSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSave = (TextView)findViewById(R.id.txt_save);;
}
public void onClick(View v) {
TextView txtSave;
txtSave = (TextView)findViewById(R.id.txt_save);
txtSave.setText("something");
}
}
and I got this error:
05-14 13:47:46.835 21949-21949/stv.wordspower E/AndroidRuntime: FATAL EXCEPTION: main
Process: stv.wordspower, PID: 21949
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
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)
Can somebody add me help how can I change dynamically?
Fragment code:
public class ProgressFragment extends Fragment {
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_progress, container, false);
return rootView;
}
public static ProgressFragment newInstance() {
Bundle args = new Bundle();
ProgressFragment fragment = new ProgressFragment();
fragment.setArguments(args);
return fragment;
}
}
The textView is on the ProgressFragment. The ProgressFragment is on the MainActivity's FrameLayout.
I just want to modify the TextView's values but I can't. I have tried these solutions, but one did not work.
other informations:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="stv.wordspower.MainActivity">
<TextView
android:text="#string/txtView_welcome"
android:textSize="30sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textAlignment="center" />
<Button
android:text="#string/btn_exit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_exit"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/btn_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btn_settings"
android:layout_above="#+id/btn_contact"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btn_contact"
android:layout_above="#+id/btn_exit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView"
android:text="#string/btn_progress" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/btn_progress"
android:layout_above="#+id/btn_settings"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/mainActivityFragmentLayout">
</FrameLayout>
<LinearLayout 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="stv.wordspower.ProgressFragment"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/txt_progresses"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txt_progresses"
android:textAlignment="center"
android:textColor="#android:color/background_dark"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txt_empty"
android:textAlignment="center"
android:textSize="30dp"
android:onClick="onClick"
android:clickable="true"/>

In onClick method, you can get fragment as following:
public void onClick(View v) {
yourFrag fragment = (yourFrag)getSupportFragmentManager().findFragmentById(R.id.fragment_id);
}
and in fragment, create a method to update the textView, so that we can call it using fragment object as following:
public void update(String s){
textView.setText(s);
}
Note: This textView should be defined in your fragment.
and call this from main activity as following:
public void onClick(View v) {
yourFrag fragment = (yourFrag)getSupportFragmentManager().findFragmentById(R.id.fragment_id);
fragment.update("foo");
}
And yes! if you are not using support library, just replace getSupportFragmentManager() by getFragmentManager().

Related

Moving from fragment to activity giving error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
findViewById returns NULL when using Fragment
(7 answers)
Closed 1 year ago.
Actually I saw a yt video of how to intent fragment and acticity and that is what I tried but don"t know how the error is coming.The error which I am having is ** java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.photoframeapp.HomeFragment.onCreateView(HomeFragment.java:31)**.I tried to sort out but I am not able to .
this is my HomeFragment.java class
public class HomeFragment extends Fragment {
TextView beginners;
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
beginners.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),mainpage.class));
}
});
return view;
}
}
this is my mainpage.java file
public class mainpage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
}
}
fragment_home.xml file
<?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=".HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="387dp"
android:alpha="0.4"
android:background="#color/Purple" />
<TextView
android:id="#+id/beginners"
android:layout_width="match_parent"
android:layout_height="72dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="-27dp"
android:layout_marginBottom="433dp"
android:freezesText="true"
android:text=" BEGINNERS CALLIGRAPHY"
android:textSize="25dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="195dp"
android:alpha="0.4"
android:background="#color/DeepPink" />
<TextView
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="-9dp"
android:layout_marginBottom="67dp"
android:text=" ADVANCED CALLIGRAPHY"
android:textSize="25dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="4dp"
android:alpha="0.4"
android:background="#color/DarkBlue" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="-8dp"
android:layout_marginBottom="261dp"
android:freezesText="true"
android:text=" INTERMEDIATE CALLIGRAPHY"
android:textSize="25dp" />
</RelativeLayout>
You have to initialize textView before using it.
View view = inflater.inflate(R.layout.fragment_home, container, false);
beginners = view.findViewById(R.id.beginners)
beginners.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),mainpage.class));
}
});

OnclickListner for fragement and activity in android

Hi I have a scenario like I have a created a Main Activity and different fragments. MainActivity I am implemented the bottom navigation bar it contains different tabs
1.Task
2.Account
3.Contact
For the above have created the different fragments above tabs we have a common button called '+'.
Now My problem is that if i opened the account fragment want to display the fragment details .In that account tab has common '+' button for all .If I click on + button want to create a new account fragment.
How to resolve it.
MainActivity:
public void initBottomNavigationItems() {
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.task:
toolbar.setTitle("Task");
fragment = new TaskFragement();
loadFragment(fragment);
return true;
case R.id.account:
toolbar.setTitle("Account");
fragment = new AccountFragement();
loadFragment(fragment);
return true;
case R.id.contact:
toolbar.setTitle("Contact");
fragment = new ContactFragment();
loadFragment(fragment);
return true;
case R.id.opportunity:
toolbar.setTitle("Opportunity");
fragment = new OpportuntityFragement();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
If click on account tab it will move to the account fragment .In the same way want if i click on fab button want to replace account fragment with create fragment .But my fab button is in activity_main not in account fragement.
AccountFragement:
public class AccountFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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);
}
}
fragment_account.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:background="#color/White">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/slivergray"
app:cardCornerRadius="8dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/White">
<ImageView
android:id="#+id/appImage"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginLeft="16dp"
android:background="#drawable/ic_account_circle_black_24dp"
android:backgroundTint="#color/gray"
android:scaleType="centerCrop"
tools:ignore="ContentDescription"/>
<TextView
android:id="#+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/appImage"
android:paddingLeft="16sp"
android:paddingRight="16dp"
android:text="Apollo Hospital"
android:textColor="#color/black"
android:textSize="18sp"
tools:ignore="RtlHardcoded"/>
<TextView
android:id="#+id/subHeaderText"
style="#style/Base.TextAppearance.AppCompat.Subhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/headingText"
android:layout_toRightOf="#+id/appImage"
android:paddingLeft="16dp"
android:text="Hospital"
android:paddingRight="16dp"
android:textColor="#color/gray"
android:textSize="15sp"/>
<TextView
android:id="#+id/subHeadingText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/subHeaderText"
android:layout_toRightOf="#+id/appImage"
android:gravity="left"
android:lines="5"
android:maxLines="5"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:text="stories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detail"
android:textColor="#color/gray"
android:textSize="14sp"/>
<TextView
android:id="#+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="⋮"
android:textColor="#color/gray"
android:layout_marginRight="10dp"
android:textAppearance="?android:textAppearanceLarge"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/subHeadingText">
<LinearLayout
android:layout_width="209dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="30dp"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:backgroundTint="#color/gray"
android:src="#drawable/ic_account_circle_black_24dp"></ImageView>
<Button
android:id="#+id/action1"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Action 1"
android:textColor="#color/gray"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="right">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:src="#drawable/ic_account_circle_black_24dp"
android:layout_marginLeft="50dp"></ImageView>
<Button
android:id="#+id/action2"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Action 2"
android:textColor="#color/gray"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</RelativeLayout>
I understand that you want to call your activity method from fragment.(from a + button in fragment).
Then you can use an interface in your fragment to get callback in activity.
public class AccountFragment extends Fragment {
OnFabClickListener listener;
// Container Activity must implement this interface
public interface OnFabClickListener{
public void onCreateNewAccount();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener= (OnFabClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFabClickListener");
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onCreateNewAccount();
}
});
}
...
}
Then in your activity implement the interface this way.
public class MainActivity extends AppCompatActivity implements OnFabClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
}
#Override
public void onCreateNewAccount() {
//Add your new account creation code here like loadFragment
}
}

All Objects within a fragment returning null

My fragment is not initialising objects correctly. I'm struggling to see why.
Many StackOverflow questions have all suggested adding the following line in the fragment's OnCreateView() should initialise objects correctly.
mList = (ListView) view.findViewById(R.id.locationList);
It doesn't seem to be working, as I can see in debug that my Switch and ListView are returning as null. Within my fragment's xml, I have a Switch and ListView id's of lostToggle and locationList appropriately, so they should point to these objects. I'm struggling to see why this is happening. Any help is appreciated.
page2_fragment.java
public class page2_fragment extends Fragment {
private Switch mToggle;
private ListView mList;
private ArrayAdapter<String> mLocationArrayAdapter;
private ArrayList<String> items = new ArrayList<String>();
public page2_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page2_fragment, container, false);
mToggle = (Switch) view.findViewById(R.id.lostToggle);
mList = (ListView) view.findViewById(R.id.locationList);
mLocationArrayAdapter = new ArrayAdapter<>(
getActivity().getApplicationContext(),
android.R.layout.simple_expandable_list_item_1,
items);
setupLostToggle();
// Inflate the layout for this fragment
return view;
}
public ArrayAdapter getArrAdapter() { return mLocationArrayAdapter; }
public ListView getList() { return mList; }
public ArrayList<String> getArrayList() { return items; }
public Switch getToggle() { return mToggle; }
private void setupLostToggle() {
//Add "Lost" toggle functionality
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
Log.d("Toggle: ","Enabled");
} else {
// The toggle is disabled
Log.d("Toggle: ","Disabled");
}
}
});
}
}
page2_fragment.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.robertdavis.aloost.page2_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/t1_colorPrimaryDark"
android:baselineAligned="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/activity_vertical_margin"
android:text="#string/keyword_location"
android:textAllCaps="true"
android:textColor="#android:color/white"/>
</LinearLayout>
<android.support.v7.widget.CardView
android:id="#+id/main_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginBottom="8dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|end"
android:gravity="top"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="9dp"
android:layout_weight="0.25"
android:text="I'm looking for"/>
<Spinner
android:id="#+id/spinnerCategory"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_weight="0.75"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|end"
android:gravity="top"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="within"/>
<Spinner
android:id="#+id/spinnerRadius"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="kilometres." />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|end"
android:gravity="top"
android:orientation="horizontal">
<Button
android:id="#+id/button_getPlacesData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:onClick="getPlacesData"
android:text="Go"
android:textAllCaps="true" />
<Switch
android:id="#+id/lostToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="22dp"
android:text="Lost? "
android:layout_centerHorizontal="true"/>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/results_list_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="30dp"
app:cardCornerRadius="4dp">
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v7.widget.CardView>
</LinearLayout>
Edit: Logcat data (as requested)
12-10 06:57:20.088 18139-18139/com.example.robertdavis.aloost E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.robertdavis.aloost, PID: 18139
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.robertdavis.aloost.AsyncTaskParseJson.onPostExecute(AsyncTaskParseJson.java:95)
at com.example.robertdavis.aloost.AsyncTaskParseJson.onPostExecute(AsyncTaskParseJson.java:16)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
try initialising object in onViewCreated(View view, Bundle savedInstanceState)
method

Changing fragments dynamically - java.lang.IllegalArgumentException: No view found for id

I'm learning how to program in Android and I'm having some problems about changing my fragments. I tried almost all the solutions that I found here but they aren't working.
Here is my layout that I'm trying to show in screen:
fragment_result.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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.ic.projeto_final.ResultFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/resultView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".90"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:layout_width="0dp"
android:layout_weight=".10"
android:layout_height="wrap_content"
android:text="setaesq - pegar cod ascii"
android:id="#+id/btnPrevious"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_weight=".80"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textAlignment="center"
android:textSize="25dp"
android:id="#+id/fileName" >
</TextView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textAlignment="center"
android:textSize="25dp"
android:id="#+id/fileDistance" >
</TextView>
<ImageView
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fileImage"
/>
</LinearLayout>
<Button
android:layout_width="0dp"
android:layout_weight="0.1"
android:layout_height="wrap_content"
android:text="seta dir pegar cod ascii"
android:id="#+id/btnNext"
/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fazer nova consulta"
android:layout_gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:id="#+id/btnNovaConsulta"/>
</LinearLayout>
</FrameLayout>
And the class related:
ResultFragment.java
public class ResultFragment extends Fragment {
public ResultFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_result, container, false);
TextView fileName = (TextView) rootView.findViewById(R.id.fileName);
TextView fileDistance = (TextView) rootView.findViewById(R.id.fileDistance);
ImageView imageName = (ImageView) rootView.findViewById(R.id.fileImage);
Button btnPrevious = (Button) rootView.findViewById(R.id.btnPrevious);
Button btnNext = (Button) rootView.findViewById(R.id.btnNext);
return rootView;
}
}
And this is the part in my mainActivity that tries to change the fragment displayed:
MainActivityFragment.java
btnConsulta.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/* Others pieces of code that not affect this part */
ResultFragment result = new ResultFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.resultView, result);
transaction.addToBackStack(null);
transaction.commit();
}
}
Currently, the error shown in my logcat is:
java.lang.IllegalArgumentException: No view found for id 0x7f0a000f (com.example.ic.projeto_final:id/resultView) for fragment ResultFragment{143a9831 #0 id=0x7f0a000f}
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:886)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
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:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And I also tried to use getFragmentManager() instead of getChildFragmentManager(), associating the id to the FrameLayout in fragment_result.xml, but it doesn't work too.
If there is anything missing that I need to show in order to solve the problem, just let me know
In your main activity xml file put in it this:
< FrameLayout
android:id = "#+id/resultView"
android:layout_width = "wrap_content"
android_layout_hight = "match_parent"
/>

Change a particuar view in Fragment

I am new to android developing and I am currently stumped at this situation.
Is there a way to change a particular child view of a fragment?
For example, I have a TextView and Button in a Fragment. Now after inflating this fragment and committing it, I would like to only change the text of the TextView based on the user input.
EDIT: The same layout is used to create multiple fragments. I would like to just change the TextView of a particular Fragment.
MainActivity Code:
public class MainActivity extends Activity {
Button bt;
EditText et;
LinearLayout ly;
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.badd);
ly=(LinearLayout) findViewById(R.id.lay_ver);
et=(EditText) findViewById(R.id.etadd);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// multiple fragments are created
MyFragment f=new MyFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction t=fm.beginTransaction();
t.add(R.id.sv1, f, "hi");
t.commit();
et.setText("");
}
});
//would like to change the text of the textview of the fragment
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Fragment Code:
public class MyFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.frag_lay, null);
return v;
}
}
activity_main XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lay_ver"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/lay_hor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/etadd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="80"
android:hint="Enter Subject"
android:paddingTop="20dp" />
<Button
android:id="#+id/badd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="Add" />
</LinearLayout>
<ScrollView
android:id="#+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/sv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layfrag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.53"
android:text="HiHow"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
You can add a list of Fragments in your activity and each fragment to the list when you create them. Then you can get the fragment you want to change and do as cdblades said :
View parent = fragment.getView();
View childTextView = (TextView)parent.findViewById(R.id.myChildTextView);
But why are you adding the fragments in the same container?
The base View class has the findById() method that you can use to get a reference to child views like so:
View parent = fragment.getView();
View childTextView = (TextView)parent.findViewById(R.id.myChildTextView);

Categories

Resources