<?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="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/fragment1"
android:name="ankit.fairmatrix.in.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mText"
android:text="Hello World!" />
</LinearLayout>
How can I access TextView inside the activity (here mText ) from Fragment class MyListFragment?
(TextView) ((MyActivity)getActivity).findViewById(R.id.mText);
But better to do something like this:
public class MainActivity extends Activity implements OnTextChangeListener {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id. mText);
}
#Override
public void changeText(String text){
textView.setText(text);
}
}
Fragment code
public class MyListFragment extends Fragment {
interface OnTextChangeListener{
void changeText(String text);
}
private OnTextChangeListener onTextChangeListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof OnTextChangeListener){
onTextChangeListener = (OnTextChangeListener)activity;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.chat_list, container, false);
}
public void something(){
onTextChangeListener.change("Hello");
}
}
Related
I have seen several memory leak posts here and I think this one is a bit different. I have a floatingactionbutton in my fragment, whenever I navigate to another fragment using the Navigation graph the fab is reported to be leaking by leakcanary below is my xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="#+id/coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.store.StoreFragment">
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/small_margin"
app:cardElevation="#dimen/normal_elevation"
app:shapeAppearanceOverlay="#style/ShapeAppearanceOverlayLargeCutLeftTopCorner">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeToRefresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.core.widget.NestedScrollView
android:id="#+id/nestScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fadingEdge="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ViewStub
android:layout_width="match_parent"
android:id="#+id/layoutCategories"
android:layout_height="wrap_content"
android:inflatedId="#+id/panel_layoutCategories"
android:layout="#layout/store_layout_categories" />
<ViewStub
android:id="#+id/layoutDeals"
android:layout_height="wrap_content"
android:inflatedId="#+id/panel_layoutDeals"
android:layout_width="match_parent"
android:layout="#layout/store_layout_deals" />
<ViewStub
android:id="#+id/layoutCollections"
android:layout_height="wrap_content"
android:inflatedId="#+id/panel_layoutCollections"
android:layout_width="match_parent"
android:layout="#layout/store_layout_collections" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/btnGoToCart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:text="#string/cart"
android:textColor="#android:color/white"
android:textStyle="bold"
app:backgroundTint="#color/colorAccent"
app:elevation="#dimen/large_elevation"
app:icon="#drawable/ic_shopping_cart_24px"
app:iconTint="#android:color/white"
app:layout_anchor="#id/nestScrollView"
app:layout_anchorGravity="bottom|end"
app:shapeAppearanceOverlay="#style/ShapeAppearanceOverlayLargeCutLeftTopCorner" />
The btnGoToCart is the problematic fab
And my fragment looks like
public class StoreFragment extends Fragment implements View.OnClickListener {
#BindView(R.id.btnGoToCart)
ExtendedFloatingActionButton btnGoToCart;
private StoreFragmentViewModel storeFragmentViewModel;
public StoreFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_store, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
btnGoToCart.setOnClickListener(this);
loadData();
}
private void loadData() {
disposables.add(SharedPreferencesUtils
.getInstance(getContext())
.isLoggedIn()
.subscribeWith(new DisposableSingleObserver<Boolean>() {
#Override
public void onSuccess(Boolean aBoolean) {
if (aBoolean)
storeFragmentViewModel.fetchProductCategories();
}
#Override
public void onError(Throwable e) {
}
}));
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
//I tried this hoping it would work nothing
btnGoToCart.clearAnimation();
((ViewGroup) btnGoToCart.getParent()).removeView(btnGoToCart);
btnGoToCart = null;
}
#Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
}
}
I tried doing this in the onStop
//I tried this hoping it would work nothing
btnGoToCart.clearAnimation();
((ViewGroup) btnGoToCart.getParent()).removeView(btnGoToCart);
btnGoToCart = null;
But it did not work
Below are the snippets from Leak canary
Can you share the ExtendedFloatingActionButton implementation? Maybe your doing something wrong there.
Also if your using ButterKnife in a Fragment you should use:
private Unbinder unbinder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fancy_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
// TODO Use fields...
return view;
}
#Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
BINDING RESET Fragments have a different view lifecycle than
activities. When binding a fragment in onCreateView, set the views to
null in onDestroyView. Butter Knife returns an Unbinder instance when
you call bind to do this for you. Call its unbind method in the
appropriate lifecycle callback.
I am creating an app in which in portrait mode I have an activity that has a fragment which contains a listview and on clicking on that listview, Second activity is called to show the data using second fragment but the problem is that when second fragment, i.e. Frag2 is called its onActivityCreated() method is not getting called. Why so?
MainActivity.xml
portrait mode
<LinearLayout 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"
tools:context="com.example.ankit.fragprac2.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/frag1"
android:name="com.example.ankit.fragprac2.Frag1"
/>
</LinearLayout>
landscape mode
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/frag1"
android:name="com.example.ankit.fragprac2.Frag1"
android:layout_weight="1"/>
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/frag2"
android:name="com.example.ankit.fragprac2.Frag2"
android:layout_weight="1"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements Frag1.Comm {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void respond(int i)
{
FragmentManager fm=getFragmentManager();
Frag2 fg2= (Frag2) fm.findFragmentById(R.id.frag2);
if(fg2!=null && fg2.isVisible())
{
fg2.setData(i);
}
else
{
Intent in=new Intent(this,SecondActivity.class);
in.putExtra("position",i);
startActivity(in);
}
}
}
Fragment1.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list"/>
</RelativeLayout>
Fragment1.java
public class Frag1 extends Fragment {
ListView lv;
Comm c1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_frag1,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] s=getResources().getStringArray(R.array.topics);
c1 = (Comm) getActivity();
lv = getActivity().findViewById(R.id.list);
lv.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,s));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
c1.respond(i);
}
});
}
interface Comm
{
void respond(int i);
}
}
Fragment2.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text1"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#000"/>
</RelativeLayout>
Fragment2.java
public class Frag2 extends Fragment {
TextView t;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_frag2,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(),"OAC",Toast.LENGTH_SHORT).show();
t=getActivity().findViewById(R.id.text1);
// s1=new String[getResources().getStringArray(R.array.data).length];
// Toast.makeText(getActivity(),""+s1.length,Toast.LENGTH_SHORT).show();
if(savedInstanceState!=null)
{
String s=savedInstanceState.getString("data",null);
t.setText(s);
}
}
public void setData(int i)
{ String[] s1 =getResources().getStringArray(R.array.data);
t.setText(s1[i]);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("data",t.getText().toString());
}
}
SecondActivity.xml
<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"
tools:context="com.example.ankit.fragprac2.SecondActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/frag21"
android:name="com.example.ankit.fragprac2.Frag2"/>
</RelativeLayout>
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle b= getIntent().getExtras();
if(b!=null)
{
i= b.getInt("position",0);
}
FragmentManager fm=getFragmentManager();
Frag2 fga2= (Frag2) fm.findFragmentById(R.id.frag21);
fga2.setData(i);
}
}
In the SecondActivity.onCreate(), move this code:
FragmentManager fm=getFragmentManager();
Frag2 fga2= (Frag2) fm.findFragmentById(R.id.frag21);
fga2.setData(i);
To SecondActivit.onStart().
When using fga2.setData(i) in the onCreate, the Activity is not created yet; it is being created. Hence the onActivityCreated() method of the fragment has not been called yet.
Other notes:
Activity should extent FragmentActivity instead of AppCompatActivity.
you can use getSupportFragmentManager().findFragmentById to get the fragment.
Also see the Activity Life Cycle and Fragment LifeCycle.
Hope this helps.
I had an activity with a Listview containing text and green squares. I finally changed my mind and modified my code to use a fragment instead of an activity. But then my text color changed and I can't see the green squares anymore. I didn't changed anything in my list code or the color of the text so I don't understand what's happening.
Thank you for your help.
MainActivity is only used as a fragment container :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.ll_container);
if (fragment == null) {
fragment = new PollutionLevelsFragment();
fm.beginTransaction()
.add(R.id.ll_container, fragment)
.commit();
}
}
}
MainActivity layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The fragment class
public class PollutionLevelsFragment extends Fragment implements PollutionLevelsFragmentMVP.View {
private PollutionLevelAdapter plAdapter;
#BindString(R.string.city)
String city;
#BindString(R.string.aqicn_token)
String authToken;
#BindView(R.id.lv_pollution_levels)
ListView lvPollutionLevels;
#Inject
PollutionLevelsFragmentMVP.Presenter presenter;
private ViewModel pollutionData;
private ArrayList<String> testbidon;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pollution_levels, container, false);
ButterKnife.bind(this,view);
// Construct the data source
ArrayList<PollutionLevel> arrayOfPollutionLevel = new ArrayList<>();
// Create the adapter to convert the array to views
plAdapter = new PollutionLevelAdapter(getActivity().getApplicationContext(), arrayOfPollutionLevel);
lvPollutionLevels.setAdapter(plAdapter);
return view;
}
#Override
public void onStart() {
super.onStart();
presenter.setView(this);
presenter.loadData(city, authToken);
}
#Override
public void onStop() {
super.onStop();
presenter.rxUnsubscribe();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((App) getActivity().getApplication()).getComponent().inject(this);
}
#Override
public void updateData(ViewModel viewModel) {
this.pollutionData = viewModel;
ArrayList<PollutionLevel> pollutionLevels = viewModel.getAllPolluants();
for(PollutionLevel pl : pollutionLevels) {
plAdapter.add(pl);
}
}
}
The fragment layout
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:id="#+id/lv_pollution_levels"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
The ArrayAdapter for the ListView
public class PollutionLevelAdapter extends ArrayAdapter<PollutionLevel> {
#BindView(R.id.tv_name)
TextView tvName;
#BindView(R.id.tv_value)
TextView tvValue;
public PollutionLevelAdapter(Context context, ArrayList<PollutionLevel> pollutionLevels) {
super(context,0,pollutionLevels);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_pollution, parent, false);
}
View view = convertView;
ButterKnife.bind(this,view);
PollutionLevel pollutionLevel = getItem(position);
tvName.setText(pollutionLevel.getName());
tvValue.setText(pollutionLevel.getValue());
return view;
}
}
My list item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_warning"
android:layout_width="20dp"
android:layout_height="20dp"
app:srcCompat="#drawable/rectangle"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical"
android:text="TextView"/>
<TextView
android:id="#+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical"
android:text="TextView"/>
This is the code of the layout the Activity class that rendered the Listview correctly (so before I switched from an activity to a fragment). I didn't put the code of the Listview adapter here since it didn't change :
Activity
public class PollutionLevelsActivity extends AppCompatActivity implements PollutionLevelsActivityMVP.View {
private PollutionLevelAdapter plAdapter;
#BindString(R.string.city)
String city;
#BindString(R.string.aqicn_token)
String authToken;
#BindView(R.id.lv_pollution_levels)
ListView lvPollutionLevels;
#Inject
PollutionLevelsActivityMVP.Presenter presenter;
private ViewModel pollutionData;
private ArrayList<String> testbidon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((App) getApplication()).getComponent().inject(this);
ButterKnife.bind(this);
// Construct the data source
ArrayList<PollutionLevel> arrayOfPollutionLevel = new ArrayList<>();
// Create the adapter to convert the array to views
plAdapter = new PollutionLevelAdapter(this, arrayOfPollutionLevel);
lvPollutionLevels.setAdapter(plAdapter);
}
#Override
protected void onStart() {
super.onStart();
presenter.setView(this);
presenter.loadData(city, authToken);
}
#Override
protected void onDestroy() {
super.onDestroy();
presenter.rxUnsubscribe();
}
#Override
public void updateData(ViewModel viewModel) {
this.pollutionData = viewModel;
ArrayList<PollutionLevel> pollutionLevels = viewModel.getAllPolluants();
for(PollutionLevel pl : pollutionLevels) {
plAdapter.add(pl);
}
}
}
Layout
<android.support.constraint.ConstraintLayout
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"
tools:context="com.livos.citypollution.pollutionlevels.PollutionLevelsActivity">
<ListView
android:id="#+id/lv_pollution_levels"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
To change Text Color add this
android:textColor="Your Color Code"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_warning"
android:layout_width="20dp"
android:layout_height="20dp"
**app:src="#drawable/rectangle"**/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical"
android:text="TextView"
android:textColor="Your Color Code"/>
<TextView
android:id="#+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_vertical"
android:text="TextView"
android:textColor="Your Color Code"/>
As i am getting. You give an adapter like:
public class PollutionLevelAdapter extends ArrayAdapter<PollutionLevel> {
#BindView(R.id.tv_name)
TextView tvName;
#BindView(R.id.tv_value)
TextView tvValue;
public PollutionLevelAdapter(Context context, ArrayList<PollutionLevel> pollutionLevels) {
super(context,0,pollutionLevels);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_pollution, parent, false);
}
View view = convertView;
ButterKnife.bind(this,view);
PollutionLevel pollutionLevel = getItem(position);
tvName.setText(pollutionLevel.getName());
tvValue.setText(pollutionLevel.getValue());
return view;
}
}
You are binding your two TextView not Your ImageView as you gave your list_item_pollution, which is having ImageView so bind your ImageView like:
#BindView(R.id.iv_warning)
ImageView iv_warning;
and in getView method set is as :
iv_warning.setBackgroundColor(Color.parseColor("your color code"));
I am sending data from one fragment to another, using interface. This works absolutely fine. Now I am trying to use onSaveInstanceState() to save the value in
a Fragment and retrieving in onCreate(). however i'm getting null in Bundle of onCreate(). P.S. everything works fine when i set the Fragment directly into the activity layout in xml. but when i set the fragment through java code into the activity, the onSaveInstanceState is failing. It is not saving the last known value. Please help. Pasting the code below. You can try it out to know the exact issue.
Fragment_A :
public class Fragment_A extends Fragment implements View.OnClickListener {
Button btnAdd;
int counter = 0;
Communicator comm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
counter = savedInstanceState.getInt("counter", 0);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm = (Communicator) getActivity();
btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", counter);
}
#Override
public void onClick(View v) {
counter++;
comm.sendData(counter);
}
}
interface Communicator{
void sendData(int i);
}
=====
Activity :
public class Activity_InterComm extends Activity implements Communicator{
FragmentManager manager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intercomm);
Fragment_A fragment_1 = new Fragment_A();
Fragment_B fragment_2 = new Fragment_B();
manager = getFragmentManager();
transaction = manager.beginTransaction();
transaction.add(R.id.frag_a, fragment_1, "Frag1");
transaction.add(R.id.frag_b, fragment_2, "Frag2");
transaction.commit();
}
#Override
public void sendData(int i) {
manager = getFragmentManager();
Fragment_B fragment_b = (Fragment_B) manager.findFragmentById(R.id.frag_b);
fragment_b.setData("Button has been clicked " + i + " times");
}
}
=====
Fragment_B :
public class Fragment_B extends Fragment {
TextView txtMessage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txtMessage = (TextView) getActivity().findViewById(R.id.txtMessage);
}
public void setData(String message){
txtMessage.setText(message);
}
}
activity_intercomm.xml :
<?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="match_parent"
android:orientation="vertical">
<!--<fragment
android:id="#+id/frag_a"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:name="android.learning.com.fragintercomm.Fragment_A"/>
<fragment
android:id="#+id/frag_b"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name="android.learning.com.fragintercomm.Fragment_B"/>-->
<LinearLayout
android:id="#+id/frag_a"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:background="#color/colorAccent"
android:orientation="vertical"/>
<LinearLayout
android:id="#+id/frag_b"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
android:orientation="vertical"/>
</LinearLayout>
the soluion I found was using getView() instead of getActivity() while initializing the button in Fragment_A. use btnAdd = (Button) getView().findViewById(R.id.btnAdd); instead of btnAdd = (Button) getActivity().findViewById(R.id.btnAdd);.
However, you can't use getView() in Fragment_B. The Textview freezes and, onSaveInstanceStat() doesn't work. Please suggest a solution.
I have successfully set up the a FragmentActivity with FragementPagerAdapter associated with ViewPager to implement two tabbed application .
One of the Tabs namely "Wave" has a text view and a button . All I want is call textview.setText method via the onClick method of button described by its xml attribute .
I do not know where should I initialize my TextView or Button , how can I get the context of Wave tab and where should I write onclick method-
public class InformationShow extends FragmentActivity {
XMLdata dataObject;
ViewPager viewPager;
PagerAdapter adpt;
Fragment temp;
TextView tv;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewPager=(ViewPager)findViewById(R.id.pager);
adpt = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adpt);
// temp=adpt.fg.findFragmentById((int)adpt.getItemId(1));
tv=(TextView)findViewById(R.id.graphWaveTextView);
bt = (Button)findViewById(R.id.button1);
}
public void changeText(View v){
tv.setText("It worked ");
}
Adapter Class
public class PagerAdapter extends FragmentPagerAdapter {
int count = 2;
CharSequence namme[] = {"Temperature","Wave"};
XMLdata data;
FragmentManager fg;
public PagerAdapter(FragmentManager fragmentManager ){
super(fragmentManager);
this.fg = fragmentManager;
}
Context context;
#Override
public Fragment getItem(int arg0) {
switch (arg0){
case 0:{
TemperatureGraphFrag temp = new TemperatureGraphFrag();
return temp;
}
case 1:{WaveHeightGraphFrag wave = new WaveHeightGraphFrag();
return wave;
}
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return namme[position];
}
}
Fragments Class
public class TemperatureGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_t, container, false);
return view;
}
}
public class WaveHeightGraphFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.graph_sig_wave_height, container, false);
return view;
}
}
fragment_main XML implemented by FragmentActicity
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#65C2C9"
android:scrollbarSize="5dp"/>
</android.support.v4.view.ViewPager>
Tab 2 Fragment XML graph_sig_wave_height
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/graphWaveTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_gravity="center"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center"
android:onClick="changeText"/>
</LinearLayout>
Tab 1 fragment layout XML graph_t
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/linearTemp"
>
<TextView
android:id="#+id/graphTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_gravity="center"
/>
</LinearLayout>
Add the following method to your WaveHeightGraphFrag class:
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
final TextView t = (TextView) view.findViewById(R.id.graphWaveTextView);
Button b = (Button) view.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
t.setText("It worked ");
}
});
}
This is what you want.