My complete code is given here. But not showing the Activity.
Showing null pointer Exception when adding clickListener().
How Can i Access the button inflated using fragment
//Cant add complete code. Showing add more details.//
public class Activity extends Activity{
private static final String KEY_SUCCESS="success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
Fragment fragment=new PlaceholderFragment();
transaction.add(R.id.container,fragment);
transaction.addToBackStack("welcome");
transaction.commit();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
Button loginButton;
private String userNameString;
private String passwordString;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
try{
loginButton= (Button) rootView.findViewById(R.id.LoginFormButton);
}catch (NullPointerException e){
e.printStackTrace();
}
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent logIntent = new Intent(getActivity(), BearerLoggedActivity.class);
startActivity(logIntent);
}
});
return rootView;
}
}
}
fragment.getView().findViewById(id)
That should do it, but I usually prefer to have all my listeners and business logic in the Fragment itself keeping the Activity as minimal possible. A small demo :
public class FirstFragment extends Fragment {
Button btn;
private OnFragmentClickListener listener;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_fragment,
container, false);
//Do stuff to the fragment view in here if you want
btn = (Button) v.findViewById(R.id.breplace);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mainIntent = new Intent(getActivity(),
MyActivity.class);
startActivity(mainIntent);
}
});
return v;
}
Hope this helps !
If I understand correctly, what you are looking for is:
fragment.getView().findViewById(id);
Please add this on your Fragment class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_layout, container, false);
//ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
//imageView.setImageResource(imageResourceId);
//imageView.setBackgroundResource(imageResourceId);
Button button = (Button) view.findViewById(R.id.btn1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mainIntent = new Intent(getActivity(),
NextActivity.class);
startActivity(mainIntent);
}
});
return view;
}
Your problem will be solved
Related
In my app I use some Fragments with some Buttons that help to navigate through different contents.
The layout I built works perfectly, but now i want to make the links for the Buttons.
MY BUTTON ID IS: buttonSP
Where can I add the onClickListener in my code snippet to open a new Activity named: Lista_Smartphone?
FragmentWithOneImage.java
public class FragmentWithOneImage extends Fragment {
private String title;
private int image;
public static FragmentWithOneImage newInstance(String title, int resImage) {
FragmentWithOneImage fragment = new FragmentWithOneImage();
Bundle args = new Bundle();
args.putInt("image", resImage);
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
image = getArguments().getInt("image", 0);
title = getArguments().getString("title");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_img, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.txtMain);
tvLabel.setText(title);
ImageView imageView = (ImageView) view.findViewById(R.id.imgMain);
imageView.setImageResource(image);
return view;
}
}
Put it on the onCreateView() method. it is equivalent of onCreate() of activity class
in onCreateView() method add below code
Context con = getActivity();
Button myButton = (Button) view.findViewById(R.id.buttonSP);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Move to Lista_Smartphone from Current fragment
startActivity(new Intent(con, Lista_Smartphone.class));
finish();
}
});
Use onActivityCreated() method , some times finding views in onCreateView() takes time and in those cases null pointer exception may arise.
public class FragmentWithOneImage extends Fragment {
TextView tvLabel;
ImageView imageView;
Button button;
public static FragmentWithOneImage newInstance(String title, int resImage) {
FragmentWithOneImage fragment = new FragmentWithOneImage();
Bundle args = new Bundle();
args.putInt("image", resImage);
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_img, container, false);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvLabel = (TextView) view.findViewById(R.id.txtMain);
imageView = (ImageView) view.findViewById(R.id.imgMain);
button=(Button)view.findViewById(R.id.button);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvLabel.setText(title);
imageView.setImageResource(image);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getActivity(),Lista_Smartphone.class);
startActivity(intent);
}
});
}
}
I have given the code i worked out and it works fine but i dont no how to add one more button to redirect to another activity
public class courses extends Fragment {
Intent intent;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.courses, container, false);
intent = new Intent(getActivity(), software_course.class);
final Button button = (Button) root.findViewById(R.id.Software_Course);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(intent);
}
});
return root;
} }
Only some tips before the real answer:
Use first capitalized letter for classes' name
Don't use first capitalized letter for ids
Don't create differents new OnClickListener instance as below, instead implement the interface
The global intent variable hasn't a lot of sense
Now here is the 'rapid' answer:
public class Courses extends Fragment {
Intent intent, anotherIntent;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.courses, container, false);
intent = new Intent(getActivity(), Software_course.class);
anotherIntent = new Intent(getActivity(), YourSecondActivityName.class);
final Button button = (Button) root.findViewById(R.id.software_Course);
final Button button2 = (Button) root.findViewById(R.id.software_Course2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(intent);
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(anotherIntent);
}
});
return root;
}
}
Here is what I recommend:
public class Courses extends Fragment implements View.OnClickListener {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.courses, container, false);
root.findViewById(R.id.software_Course).setOnClickListener(this);
root.findViewById(R.id.software_Course2).setOnClickListener(this);
return root;
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.software_Course:
startActivity(new Intent(getActivity(), Software_course.class));
break;
case R.id.software_Course2:
startActivity(new Intent(getActivity(), YourSecondActivityName.class));
break;
}
}
}
In your courses.xml add One more button with different id of other button.
<Button
android:id="#+id/hardware"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In your courses.java initialize button and use setonClickListener.
public class courses extends Fragment {
Intent intent;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.courses, container, false);
intent = new Intent(getActivity(), software_course.class);
final Button button = (Button) root.findViewById(R.id.Software_Course);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(intent);
}
});
Button Hardware=(Button)root.findViewById(R.id.Hardware_Course);
Hardware.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do stuff you want to do on click of button
intent = new Intent(getActivity(), hardware_course.class);
startActivity(intent);
}
});
return root;
}
}
This is the PagesFragment file.
public class PagesFragment extends Fragment {
public PagesFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
ImageButton s1 = (ImageButton)rootView.findViewById(R.id.speakers_1);
s1.setOnClickListener(listener);
ImageButton s2 = (ImageButton)rootView.findViewById(R.id.speakers_2);
s2.setOnClickListener(listener2);
ImageButton s3 = (ImageButton)rootView.findViewById(R.id.speakers_3);
s3.setOnClickListener(listener3);
return rootView;
}
ImageButton.OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
};
public void speak_1 (View theButton)
{
Intent i = new Intent(this.getActivity(),speaker1.class);
startActivity(i);
}
}
This is the xml file
<ImageButton
android:id="#+id/speakers_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtLabel"
android:layout_marginLeft="17dp"
android:layout_marginTop="17dp"
android:onClick="speak_1"
android:src="#drawable/speakers_1" />
How can I call speak_1? I also want to switch to another xml when the ImageButton is clicked. Thank you.
Passing different listener for each ImageButton separately is quite strange. Try to do it this way:
public class PagesFragment extends Fragment implements View.OnClickListener {
public PagesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
ImageButton s1 = (ImageButton)rootView.findViewById(R.id.speakers_1);
s1.setOnClickListener(this);
ImageButton s2 = (ImageButton)rootView.findViewById(R.id.speakers_2);
s2.setOnClickListener(this);
ImageButton s3 = (ImageButton)rootView.findViewById(R.id.speakers_3);
s3.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// here you can handle your ImageButton clicks
int id = v.getId();
if (id == R.id.speakers_1) {
speak_1();
} else if (id == R.id.speakers_2) {
speak_2();
} // etc...
}
public void speak_1() {
Intent i = new Intent(this.getActivity(),speaker1.class);
startActivity(i);
}
public void speak_2() {
Intent i = new Intent(this.getActivity(),speaker2.class);
startActivity(i);
}
}
It's also good practice to make first letter of a class name capital, it's a standard naming convention (Speaker1 instead of speaker1).
To call a method just use speak_1(arg0) inside onClick()
Example
ImageButton.OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View arg0) {
speak_1(arg0);
}
};
Do it this way:
public class PagesFragment extends Fragment implements View.OnClickListener{
public PagesFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
ImageButton s1 = (ImageButton)rootView.findViewById(R.id.speakers_1);
s1.setOnClickListener(this);
ImageButton s2 = (ImageButton)rootView.findViewById(R.id.speakers_2);
s2.setOnClickListener(this);
ImageButton s3 = (ImageButton)rootView.findViewById(R.id.speakers_3);
s3.setOnClickListener(this);
return rootView;
}
public void speak_1(View theButton)
{
Intent i = new Intent(this.getActivity(),speaker1.class);
startActivity(i);
}
#Override
public void onClick(View view) {
if(view instance of ImageButton)
speak_1(view);
}
}
public class MainFragment extends Fragment {
public static final String TAG = MainFragment.class.getSimpleName();
private static final String ABOUT_SCHEME = "settings";
private static final String ABOUT_AUTHORITY = "main";
public static final Uri ABOUT_URI = new Uri.Builder().scheme(ABOUT_SCHEME).authority(ABOUT_AUTHORITY).build();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mainbutton, container, false);
return v;
}
}
According to below link:
How to handle button clicks using the XML onClick within Fragments
public class StartFragment extends Fragment implements OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
Button b = (Button) v.findViewById(R.id.StartButton);
b.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
/* ... */
break;
}
}
}
source doesn't work too.
#J.Romero is right. Try this code, I change the onClick method and add some debug log.
public class StartFragment extends Fragment implements OnClickListener {
private static final LOG_TAG = "com.example.activity"
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_start, container, false);
if (v != null) {
Button mButton = (Button) v.findViewById(R.id.StartButton);
Log.d(TAG, "View is not null");
if (mButton != null) {
b.setOnClickListener(this);
Log.d(TAG, "mButton is not null");
}
}
return v;
}
#Override
public void onClick(View v) {
if (v == mButton) {
//do something
}
}
}
you can NOT access the UI element in onCreateView method - EVER
use onActivityCreated method , thats tell the fragment the activity is fully created and ready to interact
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button b = (Button) v.findViewById(R.id.StartButton);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
Try this way:
Button b = (Button) v.findViewById(R.id.StartButton);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Your code*/
}
});
I am having am mainActivity which consists of 3 fragment activity in a view pager .each fragment consists of edit texts .How to get the value of the edit text when swipe fragment horizontally ? I am trying to do like this.below code
public class MainActivity extends FragmentActivity {
int value = 0;
Context context;
String a = "";
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
// Set up the action bar.
//final ActionBar actionBar = getActionBar();
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mAddButtonB = (Button) findViewById(R.id.addnewB);
mAddSearchV = findViewById(R.id.addnewSearch);
mAddButtonB.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mAddSearchV.setVisibility(View.GONE);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.customviewpager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
});
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
PageZero p0;
PageOne p1;
PageTwo p2;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
p0 = new PageZero();
p1 = new PageOne();
p2 = new PageTwo();
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return p0;
case 1:
return p1;
case 2:
return p2;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
// PageZero = (Fragment1)getFragmentManager().findFragmentByTag("frag1");
public class PageZero extends Fragment {
private EditText name;
#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.componentname, container,
false);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});/*(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(), a,Toast.LENGTH_SHORT).show();
return false;
}
});*/
return view;
}
}
public class PageOne extends Fragment {
#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.componentaddress, container,
false);
return view;
}
}
public class PageTwo extends Fragment {
#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.componentmobno, container,
false);
return view;
}
}
}
when i try to access the eddittext inside pageZero class like below
name=(EditText)view.findViewById(R.id.nameTV);
a=name.getText().toString().trim();
i am getting null value.help me out..Thanks in advance.
Change the pagezero class oncreateview code like this .....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =getActivity().getLayoutInflater().inflate(R.layout.componentname,null);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
return view;
});
Return the view friend and then use default layout inflater...
At the time you click the edittext field, is there any content? Maybe you should get the text in the lost focus event of the edittext field. Thus you can enter some text first...
Example:
name.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus == false){
//get text from edittext field...
}
}
});
The way you try to get the text looks right to me. At least I do it the same way.
In the PagerAdapter's 'getItem' Method you should instantiate your fragments directly:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new PageZero();
case 1:
return new PageOne();
case 2:
return new PageTwo();
}
return null;
}
The Viewpager only calls getItem if it wants to create a new item. Unfortunatly they called the method getItem and not createItem which would be more obvious.
Get your EditText inside onClick block...
This mean change the code from:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container, false);
name=(EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});
return view;
}
To:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.componentname, container, false);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// GET EDIT TEXT HEAR:
EditText name=(EditText)view.findViewById(R.id.nameTV);
a=name.getText().toString().trim();
Toast.makeText(getApplicationContext(),a,Toast.LENGTH_SHORT).show();
}
});
return view;
}
To create a 3 different fragments with view pager you should:
1)Create FragmentActivity with view pager and view pager adapter.
public class FragmentActivity extends FragmentActivity
{
private FragmentAdapter adapter;
private ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
adapter = new FragmentAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
}
2)Create 3 Fragments with static instance
public final class Fragment1 extends Fragment
{
public static Fragment1 newInstance() {
return new Fragment1();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout layout = new LinearLayout(getActivity());
// your fragment xml view
return view;
}
}
3)Fill view pager adapter with it;
public class FragmentAdapter extends FragmentPagerAdapter
{
public InstallFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Fragment1.newInstance();
case 1:
return Fragment2.newInstance();
case 2:
return Fragment3.newInstance();
}
return null;
}
}
public class PageZero extends Fragment {
public static EditText name; //change this to public static
#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.componentname, container,
false);
name = (EditText)view.findViewById(R.id.nameTV);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
return view;
}
}
Then, you can access the public static EditText name (after the view for it has been generated of course) from another fragment like this.
public class PageOne extends Fragment {
#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.componentaddress, container,
false);
EditText page_one_text = PageZero.name; //you can get that variable in any fragment now, but using the class name of that fragment to access it
return view;
}
}
Cheers. Please mark this as the correct answer if it helps you. You have quite a bit of answers here
I tried below code. Working for me
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main_explore, container, false);
ed1 = (EditText)v.findViewById(R.id.editTextTemp);
if( ed1 == null )
{
Toast.makeText(getActivity(), "ERROR UNABLE TO GET EDIT", Toast.LENGTH_LONG).show();
}
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_main_explore, container, false);
return v;
}