//This is the TextViewExample class
public class TextViewExample {
private TextView mTextViewExample;
public TextViewExample(Activity activity) {
mActivity = activity;
mTextViewExample = (TextView)mActivity.findViewById(R.id.TextViewLayout);
}
}
//This is the Fragment class
public class TextViewFragment extends Fragment {
private TextViewExample mText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mText = new TextViewExample(getActivity());
}
}
mText is not updated in the UI! Could someone explain the correct way of displaying TextView properly from calling an activity in a fragment.
Thanks =)
You can access the Activity's TextView in the Fragment (assuming this fragment is attached to the activity) directly:
//This is the Fragment class
public class TextViewFragment extends Fragment {
private TextView mText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// you need to inflate the xml file holding this TextView.
mText = (TextView) getActivity().findViewByid(R.id.<your-text-view-id>;
// do something with your TextView
}
}
Be sure to check for getActivity() == null to avoid NPE's.
Activity:
public class MainActivity {
private TextView mTextViewExample;
protected void onCreate(Bundle savedInstanceState) {
...
mTextViewExample = (TextView) findViewById(R.id.TextViewLayout);
}
}
public void setTextViewExampleText(String text) {
mTextViewExample.setText(text);
}
TextViewFragment
public class TextViewFragment extends Fragment {
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
((MainActivity) getActivity()).setTextViewExampleText("text");
}
}
Related
Suppose, I have two fragments , FragmentA and FragmentB inside viewpager .When i click the button in fragmentA then it should be able to add the textview in another fragmentB.so, how is it possible ....please help me out.
class Myadpter extends FragmentPagerAdapter {
Fragment fragment =null;
public Myadpter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position==0){
fragment = new Post();
}
if(position==1){
fragment = new ActiveChat();
}
if(position==2){
fragment = new LastUsers();
}
if(position==3){
fragment = new Noname();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
Implement a interface to communicate between two fragments, the class where the view pager is will be a middle man
As already stated by the other user, implementing an interface is the way to go. This link Communicating with Other Fragments will explain in more detail how to achieve what you are attempting to do. Hope this solves your problem.
Do as follows:
Fragment A
public class FragmentA extends Fragment implements View.OnClickListener {
OnButtonPressed mCallback;
Button yourButton;
TextView textViewFragA;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
yourButton = findViewById(R.id.yourBtn);
textViewFragA = findViewById(R.id.textViewFragA);
yourButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.yourBtn:
mCallback.onButtonPressed(textViewFragA);
break;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnButtonPressed) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnButtonPressed");
}
}
#Override
public void onDetach() {
mCallback = null; // Avoid memory leaking
super.onDetach();
}
/**
* Interface called whenever the user has clicked on the Button
* #param textView The TextView to add in FragmentB
*/
public interface OnButtonPressed{
void onButtonPressed(TextView textView);
}
}
FragmentB
public class FragmentB extends Fragment{
TextView textViewFragB;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textViewFragB= findViewById(R.id.textViewFragB);
}
public TextView getTextViewFragB(){
return textViewFragB;
}
Activity
public class TabControllerActivity extends AppCompatActivity implements FragmentA.OnButtonPressed{
MyAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// Your Stuff
}
// Everytime the user clicks on the Button in FragmentA, this interface method gets triggered
#Override
public void onButtonPressed(TextView textViewFragA) {
FragmentB fragmentB = (FragmentB) adapter.getItem(1)/* Be careful here and get the right fragment,
otherwise the App will crash*/
// Since you got the TextView and not only the text inside of it,
// you can do whatever you want. Here for example we set the text like the textViewFragA.
//In a few words you turn the textViewFragB to the other one
fragmentB.getTextViewFragB().setText(textViewFragA.getText().toString());
}
}
Hope it will help
I am developing an app under MVP architecture as well I am using DataBinding. I have a ViewPager and in the first view-page fragment there are a few TexViews
This is my first Fragment, inside the ViewPager, who has the TextViews, note that setText() method just works on my bind() method but does not work outsite of it.
public class ViewPagerFragmentMe extends BaseFragment implements ViewPagerFragmentMeView {
private ViewPagerFragmentMePresenter mPresenter;
private FragmentViewPagerMeBinding mFragmentBinding;
private TextView mFollowers;
private TextView mFollowing;
private TextView mPost;
#Override
protected View getBindView(LayoutInflater inflater, ViewGroup container) {
mFragmentBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_view_pager_me,container,false);
View view = mFragmentBinding.getRoot();
bind(mFragmentBinding);
return view;
}
#Override
protected void getPresenter() {
Log.d(Constans.LOG,"GET PRESENTER CALLED");
mPresenter = new ViewPagerFragmentMePresenterImpl(this);
mFollowers.setText("2");//does not work
startSocialCounterUp(3,mFollowers);
}
#Override
public void startSocialCounterUp(int number, TextView textView) {
mPresenter.onSetNumberCounterUp(number,textView);
mFollowers.setText(String.valueOf(number));//does not work
}
private void bind(FragmentViewPagerMeBinding binder) {
mFollowers = binder.textViewPagerFollowersNumber;
mFollowing = binder.textViewPagerFollowingNumber;
mPost = binder.textViewPagerPostNumber;
mFollowers.setText("1");//works
}
}
This my BaseFragment
public abstract class BaseFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = getBindView(inflater,container);
getBindView(inflater, container);
getPresenter();
return view;
}
protected abstract View getBindView(LayoutInflater inflater, ViewGroup container);
protected abstract void getPresenter();
}
and finally my MVP view with the fragment related
public interface ViewPagerFragmentMeView {
void startSocialCounterUp(int number, TextView textView);
}
Is quite strange. Is not it? What I am doing wrong?
I trying out Fragment and have a problem with OnClickListener. Anyone can help?
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag_one frag1=new frag_one();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.top,frag1,"");
transaction.commit();
}
}
frag_one.java
public class frag_one extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_frag_one,container,false);
}
public class calculator extends AppCompatActivity implements View.OnClickListener {
TextView get_result;
EditText get_num1;
EditText get_num2;
Button get_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frag_one);
get_result=(TextView)findViewById(R.id.result);
get_num1=(EditText) findViewById(R.id.num1);
get_num2=(EditText) findViewById(R.id.num2);
get_button=(Button)findViewById(R.id.submit);
get_button.setOnClickListener(this);
}
public void onClick(View v) {
int num1=Integer.parseInt((get_num1.getText().toString()));
int num2=Integer.parseInt((get_num2.getText().toString()));
int sum=num1+num2;
get_result.setText(Integer.toString(sum));
}
}
}
When I run on normal activity without using Fragment. When i click the button, the calculation works. But when i move to Fragment, its not working. Please help! thx
You made a second Activity that uses the layout of the Fragment instead of actually placing the logic into the Fragment class....
public class frag_one extends Fragment implements View.OnClickListener {
TextView get_result;
EditText get_num1;
EditText get_num2;
Button get_button;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_frag_one,container,false);
get_result=(TextView)rootView.findViewById(R.id.result);
get_num1=(EditText)rootView.findViewById(R.id.num1);
get_num2=(EditText) rootView.findViewById(R.id.num2);
get_button=(Button)rootView.findViewById(R.id.submit);
get_button.setOnClickListener(this);
return rootView;
}
public void onClick(View v) {
// TODO: Check v.getId() == R.id.submit
int num1=Integer.parseInt((get_num1.getText().toString()));
int num2=Integer.parseInt((get_num2.getText().toString()));
int sum=num1+num2;
get_result.setText(Integer.toString(sum));
}
}
you not referring any view here, hope this will help you
public class ABC extends Fragment implements OnClickListener {
View view;
Context context;
Button btnClick;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
btnClick = (Button) view.findViewById(R.id.btnClick);
btnClick.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnClick:
break;
default:
break;
}
}
}
I have two fragments and I navigate by swiping between them. I want to update second fragment TextView from first fragment. Is it possibleto do that? Here's what I try to do but this doesn't worked to me.
public void updateOtherFragment(){
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.fragment_log, null); //my second fragment xml file.
TextView tv = (TextView)vi.findViewById(R.id.textLog);
tv.setText("Updated from first fragment " + info.getName());
}
The default Google way for communication between fragments is to do that through the activity that hosts them.
The FirstFragment defines a callbacks interface that the activity must implement. When the activity gets a callback it can send the information through to the SecondFragment. Just read the example code below to make this more clear:
FirstFragment.java:
This fragment has a button, which when clicked sends a callback to its activity.
public class FirstFragment extends Fragment implements View.OnClickListener {
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_first, container, false);
result.findViewById(R.id.updateButton).setOnClickListener(this);
return result;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.updateButton:
((Callbacks) getActivity()).onUpdateLogtext("This is an update from FirstFragment");
break;
default:
throw new UnsupportedOperationException();
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks))
throw new UnsupportedOperationException("Hosting activity must implement Callbacks interface");
}
public interface Callbacks {
void onUpdateLogtext(String text);
}
}
MainActivity.java:
This activity implements the FirstFragment.Callbacks interface in order to receive callbacks from FirstFragment. When it receives an onUpdateLogtext it just passes the data on to SecondFragment.
public class MainActivity extends AppCompatActivity implements FirstFragment.Callbacks {
private SecondFragment secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondFragment = (SecondFragment) getFragmentManager().findFragmentById(R.id.secondFragment);
}
#Override
public void onUpdateLogtext(String text) {
secondFragment.updateLogtext(text);
}
}
SecondFragment.java:
This just provides a public method that sets the textview with new data. And this method is used by MainActivity when it gets a onUpdateLogtext callback from FirstFragment.
public class SecondFragment extends Fragment {
private TextView tv;
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_second, container, false);
tv = (TextView) result.findViewById(R.id.textlog);
return result;
}
public void updateLogtext(String text) {
tv.setText(text);
}
}
Hello I am using Fragment in my android application. I need to get the view which I can get using.
mNoteEditText = rootView.findViewById(R.id.noteEditText);
This mNoteEditText is require to access in onBackPressed so every view reference I need to make them static variable because of Fragment class is static. I know to make every view to static variable is not good approach. How this I can make such that I dont need to make any static variable of the view.
public class NotesActivity extends Activity {
private int bookId;
private int chapterId;
private static EditText mNoteEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
// get data from intent that sent from home activity
bookId = getIntent().getIntExtra("book_id", -1);
chapterId = getIntent().getIntExtra("book_id", -1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new NoteFragment()).commit();
}
}
/**
* A note fragment containing a note layout.
*/
public static class NoteFragment extends Fragment {
public NoteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes,
container, false);
mNoteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
return rootView;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
// get database instance
MySQLiteOpenHelper db = MySQLiteOpenHelper.getInstance(this);
Notes note = new Notes();
note.setBookId(bookId);
note.setChapterId(chapterId);
note.setNote(mNoteEditText.getText().toString());
}
}
Please help and thanks in advance.
A Fragment has a Method called getView(). With it you can get the View of the Fragment as long as it is attached to an Activity.
View view = fragment.getView();
But if you are looking for a View inside the Fragment you can also just get it with findViewById() from the Activity. Again the Fragment has to be attached to the Activity for this to work.
BUT you should not do that. Nothing outside the Fragment should have anything to do with something inside the Fragment. Write public methods in the Fragment to interact with it. Try something like this:
public static class NoteFragment extends Fragment {
private EditText noteEditText;
public NoteFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_notes, container, false);
this.noteEditText = (EditText) rootView.findViewById(R.id.noteEditText);
return rootView;
}
// I added the following 3 methods to interact with the Fragment
public boolean isEmpty() {
final String text = this.noteEditText.getText().toString();
return text.isEmpty();
}
public String getText() {
return this.noteEditText.getText().toString();
}
public void setText(String text) {
this.noteEditText.setText(text);
}
}
And now in your Activity you can do this:
public class NotesActivity extends Activity {
private int bookId;
private int chapterId;
private NoteFragment noteFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
// get data from intent that sent from home activity
bookId = getIntent().getIntExtra("book_id", -1);
chapterId = getIntent().getIntExtra("book_id", -1);
if (savedInstanceState == null) {
this.noteFragment = new NoteFragment();
getFragmentManager().beginTransaction().add(R.id.container, this.noteFragment).commit();
}
// Now you can interact with the Fragment
this.noteFragment.setText("some text");
...
if(!this.noteFragment.isEmpty()) {
String note = this.noteFragment.getText();
...
}
}
}