i use tab layout matching this tutorial:
tab layout tutorial androidhive
It works fine, but when I add a button to fragment_one.xml , i cant use setOnClickListener for this button Because findViewById not work in MainActivity.java
the MainActivity bellow code:
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
the app stopped with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener' on a null object reference
Where should the button be defined and setOnClickListener?
Even though a fragment is hosted by an activity, it has its own layout (which is contained in the activity's layout) and therefore you'll have to define the fragment's view in its java class.
In most cases, a fragment would have its own Java class for you to manage and manipulate it, so in your case, it should look like this:
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
Button button=view.findViewById(R.id.myButtonInFragment);
return view;
}
}
If you'd like to access this button from its parent activity, you can achieve it by making the button public:
public class OneFragment extends Fragment{
public Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
button=view.findViewById(R.id.myButtonInFragment);
return view;
}
}
and then, access it using the fragment's instance in your activity:
OneFragment myFragment=new OneFragment();
After you have attached the fragment to the activity, you can use:
myFragment.button.setClickEnabled(false);
However, accessing fragment's children outside of the fragment is not recommended, and you should avoid it if you can.
public class MainActivity extends AppCompatActivity {
Button button;
Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new Fragment();
View view = fragment.getView();
if (view !=null) {
view.findViewById(R.id.button);
}
}
}
Related
I am trying to add a fragment to an existing layout from within the onClick method of a button in another Fragment class..
In my MainActivity I add two fragments to the layout..
public class MainActivity extends AppCompatActivity {
private Collapsebutton_Fragment cbut_frag;
private ColourView_Fragment cvw_frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbut_frag = new Collapsebutton_Fragment();
cvw_frag = new ColourView_Fragment();
//ColourView Fragment ready
//CollapseButton Fragment ready
getSupportFragmentManager().beginTransaction()
.add(R.id.container_mainactivity, cbut_frag)
.add(R.id.container_mainactivity, cvw_frag)
.commit();
}
}
One of the added fragments contains a button. When clicking that button - accessing the onClick method of the button - I want to add another fragment..
My code is the following:
public class ColourView_Fragment extends Fragment {
FragmentManager fragmentManager;
ThreeButton_Fragment tbt_fragment;
public ColourView_Fragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.colourview_fragment, container, false);
FrameLayout frameLayout = (FrameLayout)rootView.findViewById(R.id.ColourView);
frameLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.container_mainactivity, tbt_fragment)
.commit();
}
});
return rootView;
}
I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
There is an error in line
.add(R.id.container_mainactivity, tbt_fragment)
How can I correct?
You haven't initialized tbt_fragment in ColourView_Fragment
I am developing an Android application. I have a requirement like there is a button in fragment 1, when a user clicks that button result should be displayed in fragment 2. While loading the activity both fragments is attached. Here is my try:
In main activity:
public void dsp(String str) {
secondfragment f2=new secondfragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
f2.setArguments(bundle);
}
In first fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragone, container,false);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
m.dsp("clicked");
}
});
return v;
}
In second fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragtwo, container,false);
tv= (TextView) v.findViewById(R.id.textView1);
tv.setText(this.getArguments().getString("name"));
return v;
}
When communicating from Fragment to Fragment you use an interface to pass data to the Activity which in turn updates the fragment you want to change.
For Example:
In Fragment 1:
public class FragmentOne extends Fragment{
public Callback mCallback;
public interface Callback{
void onUpdateFragmentTwo(String message);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
mCallback = (Callback) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragone, container,false);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onUpdateFragmentTwo("clicked");
}
});
return v;
}
}
then in main Activity implement the interface:
public class MainActivity extends AppCompatActivity implements Callback{
FragmentTwo fragmentTwo;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ... Load views or perform logic
// ... Load Fragment Two into your container
if(savedInstanceState == null){
fragmentTwo = FragmentTwo.newInstance(new Bundle()); // use real bundle here
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_holder, fragmentTwo, "Frag2").commit();
}
}
// Interface method
#Override
public void onUpdateFragmentTwo(String message){
// Call activity method with the argument
if(fragmentTwo != null){
fragmentTwo.updateFragmentTwo(message);
}
}
}
Update
In your second fragment I typically use a static newInstance(Bundle args) method to initialize and then would use a public method to communicate from the Activity to the Fragment for example:
public class FragmentTwo extends Fragment{
public static FragmentTwo newInstance(Bundle args){
FragmentTwo fragment = new FragmentTwo();
fragment.setArguments(args);
return fragment;
}
//... Class overrides here onCreateView etc..
// declare this method
public void updateFragmentTwo(String updateText){
// .. do something with update text
}
}
Thats it, happy coding!
Here you have what the Android Documentation says about Communicating Between Fragments. Here you'll have all the necessary steps to make two or more fragments communicate securely :)
I'm trying to add an item to a ListView which is in one of my 3 tabs, the object will be created on another activity and after creating I want to return to the Tab and there's already shown the object in the ListView, I wanted to do FindViewById in the java class of the Tab but this doesn't work, does anyone know how i could do this?
Code:
Create Idea Activity
public class CreateIdeaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_idea);
final EditText title = (EditText) findViewById(R.id.ideaTitle);
final EditText text = (EditText) findViewById(R.id.ideaText);
final Button create = (Button) findViewById(R.id.btn_create);
create.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view)
{
Idea idea = new Idea(title.getText().toString(),text.getText().toString(),"");
Manager.AddObjectToIdeaList(idea); // Manager Class: List.add(idea)
}
});
}
One of my tabs (xml contains ListView) where I want to add items from the Manager-List to the ListView (findViewById does not work):
public class ideastab_main extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_ideastab_main, container, false);
return rootView;
}
}
I have been searching this but I haven't found anything that could help me.
I have a main activity with 2 fragments which I use as tabs in my toolbar. Is there any possibility of connecting an ImageButton from a fragment in my MainActivity to an other Activity. I know how to connect Activity to Activity through an imagebuttom, i just don't know how to do it from Fragment-> Activity. Thanks.
I have an image button on my fragment, and I want to open an activity when I press that ImageButton.
public class Movies extends Fragment {
public Movies() {
// Required empty public constructor
}
ImageButton imageButton2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_movies, container, false);
imageButton2 = (ImageButton) findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLoadNewActivity = new Intent(Movies.this, Activity_Civil_War.class);
startActivity(intentLoadNewActivity);
}
});
}
}
I am getting lots of errors. I also tried doing it in the MainActivity but I get the null object exception.
MainActivity Class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
view_pager_adapter viewPagerAdapter;
ImageButton imageButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById((R.id.toolBar));
tabLayout=(TabLayout)findViewById((R.id.tabLayout));
viewPager=(ViewPager)findViewById((R.id.ViewPager));
viewPagerAdapter = new view_pager_adapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new Showcase(),"Showcase");
viewPagerAdapter.addFragments(new Movies(),"Movie List");
viewPagerAdapter.addFragments(new Menu(),"Menu");
viewPagerAdapter.addFragments(new Login(),"Login");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
Few things first :
return inflater.inflate(R.layout.fragment_movies, container, false);
If your return a value here, the rest of the code below it will not be called. What you need to do is keep a reference to it and return it at the end of your method.
Then
Intent intentLoadNewActivity = new Intent(Movies.this, Activity_Civil_War.class);
I assume that Movies is a Fragment and Activity_Civil_War is an Activity (correct me if I'm wrong).
There is no constructor in the Intent class that takes a Fragment as a parameter. What you are trying to do by calling 'this' is to get a Context. In a Fragment you can do so by calling getActivity()
If we sum things up we get :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movies, container, false);
imageButton2 = (ImageButton) findViewById(R.id.imageButton2);
imageButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLoadNewActivity = new Intent(getActivity(), Activity_Civil_War.class);
startActivity(intentLoadNewActivity);
}
});
return view;
}
i wanted to know if someone can help me solve this issue. I have a button setup and when its clicked, its supposed to navigate to another viewpager page. But everytime its clicked, the app crashes returning the error at onClick at fragmenttab2 class. Here is my Main Activity.
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
viewPager.setCurrentItem(1);
}
}
Here is the fragment containing the onClick:
public class FragmentTab1 extends SherlockFragment {
ViewPager viewPager;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity activity = getActivity();
if (activity != null) {
addListenerOnButton();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmenttab1, container, false);
return view;
}
public void addListenerOnButton() {
Button nextfrag = (Button) getView().findViewById(R.id.btn_nextfrag);
nextfrag.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((ViewPager) viewPager.findViewById(R.id.pager)).setCurrentItem(1);
}
});
}
}
The log:
E/AndroidRuntime java.lang.NullPointerException
E/AndroidRuntime com.test.seriessample.FragmentTab1$1.onClick(FragmentTab1.java:58)
your viewPager is probably null. I also see that viewPager itself is a ViewPager and in the onClick you search for another ViewPager within that ViewPager which doesn't seem right.
EDIT:
you should add something like this in your activity
public ViewPager getPager() {
return viewPager;
}
And in the onClick of your Fragment
((MainActivity) getActivity()).getPager().setCurrentItem(1);