I want to change fragments textview from activity(not fragment class).How can I do it ? I am using this code:
public void startChat() {
FrameLayout layout = (FrameLayout)findViewById(R.id.container);
layout.setVisibility(View.VISIBLE);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, new ConversationFragment());
fragmentTransaction.commit();
viewPager.setVisibility(View.GONE);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayHomeAsUpEnabled(true);
TextView nameView=(TextView)findViewById(R.id.user_name);
nameView.setText("asd");
}
This code loads conversation_fragment.xml and wants change textview,but my app is crashing.
Here conversation_fragment.xml :
<?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:orientation="vertical"
android:background="#878787" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="dfgdfgdf"
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="@+id/user_name"/>
<EditText
android:id="@+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="Gönder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getFromUser"
android:layout_marginTop="40dp"
/>
</RelativeLayout>
You can either use findFragmentById
to find your fragment and call a public method that changes the text
(ConversationFragment) getFragmentManager().findFragmentById(R.id.yourid);
or keep an instance of the class when you create it before you add it to the fragment manager
conv = new ConversationFragment()
fragmentTransaction.add(R.id.container, conv);
then just call the public method using conv
or whatever you call it
EDIT:
you use a bundle to send in data to the fragment
Bundle b = new Bundle()
b.putString("text",data)
conv.setArguments(b);
then in your fragment get the arguments with getArguments()
and pull the data from the bundle and use it however you need