I have an activity in which i desire to retrieve data (the text in some edit texts) when i click a button in my toolbar :
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
RETRIEVE EDITTEXT!!
break;
}
this is my activity :
public class ViatgeDetallTransportActivity extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transportation);
Toolbar myToolbar = (Toolbar) findViewById(R.id.tlbMenuTransportation);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("TravelApp ACtFra");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViatgeDetallTransportFragment fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment)
.commit();
}
}
And my fragment class :
public class ViatgeDetallTransportFragment extends Fragment {
public static final String ARG_ID = "id";
public ViatgeDetallTransportFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transportation, container, false);
return rootView;
}
}
With a simple layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/layout_fragment_transportation" xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Transportation"
/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTitleFragmentTransportation"/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtDescripcioFragmentTransportation"/>
<EditText
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTypeFragmentTransportation"/>
</LinearLayout>
In the activity, when I click the toolbar button "mnufragmentOk" i want to recieve the data in the edit texts, so i can create a custom object.
Keep the fragment instance as a global variable in Activity
public class ViatgeDetallTransportActivity extends AppCompatActivity{
ViatgeDetallTransportFragment fragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transportation);
Toolbar myToolbar = (Toolbar) findViewById(R.id.tlbMenuTransportation);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("TravelApp ACtFra");
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment)
.commit();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
String s=fragment.getFirstEditTextData();
break;
}
}
Impliment the getFirstEditTextData() method inside of your Fragment
You can set a TAG for your fragment:
ViatgeDetallTransportFragment fragment = new ViatgeDetallTransportFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_fragment_transportation,fragment, "MyFragment").commit();
Then you can find that instance when you click the button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
ViatgeDetallTransportFragment fragment = getSupportFragmentManager.findFragmentByTag("MyFragment");
break;
}
Finally, you can find the TextView and get it's value:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
break;
case R.id.mnufragmentOk:
ViatgeDetallTransportFragment fragment = getSupportFragmentManager.findFragmentByTag("MyFragment");
EditText editText = (EditText)fragment.getView().findViewById(R.id.my_text_view);
String string = editText.getText().toString().trim();
break;
}
plus:
don't forget to set an ID to your EditTexts:
<EditText
android:id="#+id/my_edit_text"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/edtTypeFragmentTransportation"/>
and you need to reference them in your fragment's view creation:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_transportation, container, false);
EditText editText = (EditText)rootView.findViewById(R.id.my_edit_text);
return rootView;
}
Related
I am trying to add ActionBar (Toolbar) inside fragment and then set Button to "end" of this action bar and add onClickListener on that button.
Cannot use support.v7.widget.ToolBar (I dont know why but I could not implement it)so I had to use androidx.appcompat.widget.Toolbar instead.
I could not find any source to follow.
app_bar_layout.xml:
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_app_toolbar"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
Fragment's design fragment_wall.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WallFragment"
android:background="#color/colorWhite">
<include
android:id="#+id/update_wall_page_toolbar"
layout="#layout/app_bar_layout"></include>
</FrameLayout>
Code in WallFragment.java
public class WallFragment extends Fragment {
public WallFragment() {
// Required empty public constructor
}
private Toolbar TopActivityToolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_wall, container, false);
TopActivityToolbar = v.findViewById(R.id.update_wall_page_toolbar);
TopActivityToolbar.setTitle("Príspevky");
TopActivityToolbar.setLogo(ContextCompat.getDrawable(getActivity(),R.drawable.ic_add_circle_black_24dp));
return v;
}
}
so what was the successfull answer for me:
Inside onCreate method just add setHasOptionsMenu(true);
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Inside my WallFragment.java in onCreateView I added setOnMenuItemClickListener just right after initializing the Toolbar
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflatedView = inflater.inflate(R.layout.fragment_wall, container, false);
TopActivityToolbar = inflatedView.findViewById(R.id.update_wall_page_toolbar);
TopActivityToolbar.setTitle("someTitle");
TopActivityToolbar.inflateMenu(R.menu.menu_app_actionbar_wall);
// and finally set click listener
TopActivityToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// Your code inside Toolbar onClick...
return false;
}
});
return inflatedView;
}
Do not forget to to INFLATE the menu from res/menu/...
Add Toolbar inside fragment (AndroidX),you should use the onCreateOptionsMenu() method inside fragment.
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {inflater.inflate(R.menu.example_menu, menu);
}
First,you have to call setHasOptionsMenu() within the fragment's onCreate() method:
setHasOptionsMenu(true);
//For handling item selection
You can handle menu item clicks in the onOptionsItemSelected() method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemId:
//action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Full Example code is below:
In this example One activity: Main activity:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="200dp"
android:id="#+id/fragment_id"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"
android:onClick="changeFragment"
android:layout_gravity="center"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new FirstFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_id, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void changeFragment(View view) {
loadFragment(new SecondFragment());
}
}
There is two fragment in this example:
FirstFragment and SecondFragment.
FirstFragment.java :
public class FirstFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.first_layout,container,false);
return view;
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.first_item_menu, menu);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
//For handling item selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemId:
Toast.makeText(getContext(),"First Fragment item",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondFragment.java
public class SecondFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.second_frag,container,false);
return view;
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.second_item_menu, menu);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
//For handling item selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemId1:
Toast.makeText(getContext(),"Second Fragment item",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
In menu file,app:showAsAction="ifRoom" in your menu item.Below is example code for menu file.
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/itemId"
android:icon="#drawable/ic_apps_black_24dp"
android:title="First"
app:showAsAction="ifRoom">
</item>
</menu>
First of all, to make it work you need to call this code in onCreateView callback of fragment that is needed to have a menu;
setHasOptionsMenu(true);
Then you are able to inflate the menu and set listener to handle clicks on item:
inflater.inflate(*R.menu.your_menu_resource*, menu);
After that you are able to override onCreateOptionsMenu and onOptionsItemSelected to provide logic that is needed:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.toolbar, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.toolbar_seetings) {
Toast.makeText(getContext(), "Menu item was clicked", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
After that you just need to handle App Bar visibility, so you need to place the code in onCreateView and it will look like that:
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
((AppCompatActivity) getActivity()).getSupportActionBar().show();
return inflater.inflate(R.layout.fragment_home, container, false);
}
I'm new to Android development. I just created navigation drawer with fragment of my own (simple calculator app). In that fragment I have added a click method for the buttons. But that is not working.
Note: I have defined the onclick method in xml view
calculator fragment:
public class SimpleCalcActivity extends Fragment {
private TextView mDisplay;
private boolean mDisplayIsEmpty = true;
private boolean mFirstNumberReceived;
private boolean mNumberEntered;
private boolean mPointEntered;
private double sNum1;
private double sNum2;
private static OperationsAndFunctions.OperEnum sOperation;
private static OperationsAndFunctions.FuncEnum sFunction;
private Animation anim;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_simplecalc,null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDisplay = (TextView) view.findViewById(R.id.resultview);
mDisplay.setText("0");
}
public void num_Clicked(View view) {
Button button = (Button) view;
int number = 0;
switch (button.getId()) {
case R.id.n_one:
number = 1;
anim = AnimationUtils.loadAnimation(getContext(),
R.anim.btn_anim);
button.startAnimation(anim);
break;
case R.id.n_two:
number = 2;
anim = AnimationUtils.loadAnimation(getContext(),
R.anim.btn_anim);
button.startAnimation(anim);
break;
...
}
...
}
calculator view:
<Button
android:id="#+id/o_root"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:background="#drawable/button"
android:text="#string/root"
android:onClick="func_Clicked"
android:textStyle="bold"
android:textSize="30sp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:textColor="#android:color/white"/>
<Button
android:tag="nums"
android:id="#+id/n_seven"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:background="#drawable/button"
android:text="#string/_7"
android:onClick="num_Clicked"
android:textStyle="bold"
android:textSize="30sp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:textColor="#android:color/white"/>
Navigation drawer:
...
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_simple_calc) {
fragment = new SimpleCalcActivity();
}
}
if (fragment != null){
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.screen_area, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
...
I have tried setOnClickListener Method, it does not worked for me
I'm looking for your help. Thanks in advance.
Your fragment code is wrong. Try this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_dialog, container, false);
cancelAction = view.findViewById(R.id.cancelActionId);
cancelAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do anything.
}
});
return view;
}
Your aren't Return the view.
Try to write code with this structure, your problem will be gone.
You should define num_Clicked() method in Your Activity not Fragment.
Move the method to the activity in which you are using that fragment
Hi I am new to Android so if my question seems redundant, please bear with me as I was unable to find a proper answer anywhere. I have a main activity with 4 tabs on the bottom navigation bar and three fragments to populate these tabs. Now when I start a child of any of these fragments, the child is not displayed with the navigation bar. How do i achieve this?
MainActivity.class main function
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
// BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = TabOneFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = TabTwoFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = TabThreeFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace( R.id.frame_layout,selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, TabOneFragment.newInstance());
transaction.commit();
TabActivity
public class TabOneFragment extends Fragment {
ArrayList<SettingsClass> data;
private Button send;
ListView listView;
public static TabOneFragment newInstance() {
TabOneFragment fragment = new TabOneFragment();
return fragment;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_tab_one_fragment, container, false);
return v;
}
#Override
public void onViewCreated(View view, #Nullable final Bundle savedInstanceState) {
data = new ArrayList<>();
data.add(new SettingsClass("Option1", R.drawable.o1));
data.add(new SettingsClass("Option2", R.drawable.o2));
listView = view.findViewById(R.id.listView);
MyAdapter adapter = new MyAdapter(getActivity().getApplicationContext(), data);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(getActivity().getApplicationContext(),ChildActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "NO_CONTACT"));
startActivity(intent);
break;
}
}
}
});
The ChildActivity is not created with the navigation bottom tab. Can anybody guide me??
layout for tab one:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView">
</ListView>
</RelativeLayout>
I'm trying to put a FAB in a ViewPager tab, but I get this error (and only this):
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
It was wroking fine when I had the FAB in the activity_main.xml
MainActiviy:
private FloatingActionButton fabButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
// Initializing Floating Action Button
fabButton = (FloatingActionButton) findViewById(R.id.fabButton);
fabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "FAB was pressed!", Snackbar.LENGTH_SHORT)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
}
})
.show();
}
});
...
}
PageFragment used to sort the different tabs:
public class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
System.out.println(">> mPage = " + mPage); //Testing
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SampleFragmentPagerAdapter sampleFragmentPagerAdapter = new SampleFragmentPagerAdapter(getFragmentManager(), getContext());
View view;
switch (mPage) {
case 1:
view = inflater.inflate(R.layout.tab1_frag, container, false);
return view;
case 2:
view = inflater.inflate(R.layout.tab2_frag, container, false);
return view;
case 3:
view = inflater.inflate(R.layout.tab3_frag, container, false);
return view;
default:
view = inflater.inflate(R.layout.fragment_page, container, false);
return view;
}
}
}
tab_2frag xml file for the particular tab:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Tab 2"
android:textSize="40sp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="#dimen/fab_margin_bottom"
android:layout_marginEnd="#dimen/fab_margin_end"
android:src="#mipmap/ic_add_white_24dp"
app:fabSize="normal" />
</FrameLayout>
can anyone help?
Dont use listener.
In your xml:
android:onClick:"nameOfMethod"
In your Activity:
public void nameofMethod(View v){
//button Clicked
}
Your FloatingActionButton is in a fragment layout, but you are trying to find it in the MainActivity's onCreate(). findViewById(R.id.fabButton) returns null and thus causing the error when you set a click listener on it in the MainActivity.
You may call it in the onCreateView() of the fragment instead if you want to do it programatically
view = inflater.inflate(R.layout.tab2_frag, container, false);
fabButton = (FloatingActionButton) view.findViewById(R.id.fabButton);
fabButton.setOnClickListener(new View.OnClickListener() {...} );
return view;
Hi here you can see my code.
My probleme is : with this code my EditText and my Button field are null so i can't do anithing with them.
Plz can you help me to access to this button.
For the activity it's autogenerated by eclipse.
public class MainActivity extends ActionBarActivity {
private EditText commentaire;
private Button addReleve;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
this.commentaire = (EditText) findViewById(R.id.commentaire);
this.addReleve = (Button) findViewById(R.id.addReleve);
addReleve.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Toast toast = Toast.makeText(getApplicationContext(), "LOL", Toast.LENGTH_LONG);
toast.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void resetInterface(){
this.commentaire.setText("");
this.addReleve.setEnabled(true);
}
}
XML Layout (fragment_main.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.relevegps.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="Relevé GPS"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/addReleve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="92dp"
android:text="Ajouter le relevé" />
<EditText
android:id="#+id/commentaire"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/commentaire"
android:layout_centerHorizontal="true"
android:layout_marginBottom="26dp"
android:text="Commentaire" />
</RelativeLayout>
try this also.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
EditText commentaire = (EditText) rootView.findViewById(R.id.commentaire);
Button addReleve = (Button) rootView.findViewById(R.id.addReleve);
commentaire.setText("");
addReleve.setEnabled(true);
return rootView;
}
// Also this goes in this class
public void resetInterface(){
this.commentaire.setText("");
this.addReleve.setEnabled(true);
}
}
Your problem is that those two views are in your Framgent's xml and you can only find those in that fragment. So just move the commentaire and addReleve specific stuff to your fragment class.
public static class PlaceholderFragment extends Fragment {
// Variables moved from MainActivity to here
private EditText commentaire;
private Button addReleve;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
// To get views in fragment you need the base view (=rootView)
// Example
this.commentaire = (EditText) rootView.findViewById(R.id.commentaire);
// Put the code in here !
// ...
return rootView;
}
// Also this goes in this class
public void resetInterface(){
this.commentaire.setText("");
this.addReleve.setEnabled(true);
}
}