Using TextWatcher with Multiple Layout Files - java

New programmer here. I want the Add button on my screen to enable only when all fields are non-empty. However, adding a TextWatcher is making the screen crash. Asking elsewhere, it seems I shouldn't try to access my EditText with my ContentView set to activity_add_grade. But I need help understanding the right way to do things.
The template/tutorial I followed had me create 2 xml files per activity. As seen below, my AddClass sets the contentView to activity_add_grade and then inflates fragment_add_grade, which is where my screen design and views are. So the problem with accessing my EditText views from onCreate is that my ContentView is not set to the xml that contains the views. So where should I set my listeners instead? And why are there two xmls anyway? I'd like to understand more and follow the best practice. Thanks!
AddClass -- the java for the activity in question
public class AddClass extends ActionBarActivity {
DBAdapter db = new DBAdapter(this);
private EditText editText1;
private EditText editText2;
public TextWatcher watcher = new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
checkFieldsForEmptyValues();
}
#Override
public void afterTextChanged(Editable editable) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_grade);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
// setContentView(R.layout.fragment_add_grade); //Tried this. Doesn't work
editText1 = (EditText)findViewById(R.id.editTitle);
editText2 = (EditText)findViewById(R.id.editCredit);
editText1.addTextChangedListener(watcher);
editText2.addTextChangedListener(watcher);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_grade, menu);
//Code here for spinners on screen. Removed for space
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);
}
private void checkFieldsForEmptyValues() {
Button b = (Button)findViewById(R.id.addClassButton);
System.out.println("in the check fields thing");
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
if(s1.isEmpty() || s2.isEmpty()) {
b.setEnabled(false);
} else {
b.setEnabled(true);
}
}
// THIS WORKS -- the method is bigger, but I shortened it for space.
public void createNewClass(View v) {
EditText titleTxt = (EditText)findViewById(R.id.editTitle);
//ToStrings
String titleStr = titleTxt.getText().toString();
}
/**
* 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_add_grade,
container, false);
return rootView;
}
}

Well the view you are looking for is in your fragment's layout, so you should handle that view inside your fragment.
Option A:
remove all EditText-related code from your Activity onCreate method. Create fields watcher and editText1, editText2 inside the Fragment. So your PlaceholderFragment code should look more or less like this:
public static class PlaceholderFragment extends Fragment {
EditText editText1, editText2;
public TextWatcher watcher = new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
checkFieldsForEmptyValues();
}
#Override
public void afterTextChanged(Editable editable) {
}
};
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
editText1 = (EditText) rootView.findViewById(R.id.editTitle);
editText1.addTextChangedListener(watcher);
editText2 = (EditText) rootView.findViewById(R.id.editCredit);
editText2.addTextChangedListener(watcher);
return rootView;
}
}
Option B:
Since it looks like your fragment is the autogenerated one from eclipse and you may not want to use fragments in your code you can do this:
Drop your fragment code & layout and move the edittexts from your fragment layout in to your activitiy layout. Then your onCreate code of the Activity should work.

Related

Modify Fragment's views from MainActivity

I am trying to implement swipe views with android. I am using a ViewPager with two tabs containing fragments. In my onCreate() method, I am trying to read from a sharedPrefferences and according to what i am getting, i want to change text and visibility to some child views of the parent view of the first fragment. Unfortunately i am always getting NullPointerException when i am trying to access fragments views.
My sample code from the one of the two fragments is given below. Could you please help me ? Is there a better way to do so?
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
context = getApplicationContext();
myTabPagerAdapter = new TabPagerAdapter(getSupportFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.pager);
myViewPager.setAdapter(myTabPagerAdapter);
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(MainActivity.this, "Selected page position: " + position, Toast.LENGTH_SHORT).show();
getActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
myViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
actionBar.addTab(actionBar.newTab().setText("Spot Position").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Track Vehicle").setTabListener(tabListener));
//Get saved latitude and longitude from sharedPreferences
sharedPref = context.getSharedPreferences("net.ddns.drimou.bachelorthesis", Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
#Override
protected void onStart() {
super.onStart();
getSharedPreferencesOnStart();
}
public void getSharedPreferencesOnStart() {
String s = myTabPagerAdapter.makeFragmentName(myViewPager.getId(),myViewPager.getCurrentItem());
SpotPosition sp = (SpotPosition) myTabPagerAdapter.getItem(0);
sp.setSettings();//In this call i am getting null pointer
...}
Fragment A
public class SpotPosition extends Fragment {
TextView locationTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View spotPosition = inflater.inflate(R.layout.spot_position, container, false);
return spotPosition;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setSettings(){
locationTextView = (TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
TabPagerAdapter
public class TabPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private View mCurrentView;
private SpotPosition sp = null;
private static int NUM_ITEMS = 2;
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragment for SpotPosition myViewPager
return new SpotPosition();
case 1:
//Fragment for TrackVehicle myViewPager
return new TrackVehicle();
}
return null;
}
#Override
public int getCount() {
return NUM_ITEMS; //Number of Tabs
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
sp = (SpotPosition)object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return "Spot Position";
case 1:
return "Track Vehicle";
default:
return null;
}
}
public String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public View getCurrentView(){
return this.mCurrentView;
}
public SpotPosition getCurrentSpotPosition(){
return this.sp;
}
Feel free to ask if something is not understood. Thank you
As far as I understand you call setSettings from you activity, to change views in you fragment. You did not provide stacktrace and i assume you problem - attempt to change view after onPause was called in offcreen fragment. There are several ways to deal with it.
First of all dont call to views dirrectly.
On activity
public void getSharedPreferencesOnStart() {
String s = myTabPagerAdapter.makeFragmentName(myViewPager.getId(),myViewPager.getCurrentItem());
SpotPosition sp = (SpotPosition) myTabPagerAdapter.getItem(0);
// sp.setSettings();//In this call i am getting null pointer
SharedPreferences prefs = getSharedPreferences("message",MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean("say_hello",true")
editor.commit();
...}
in fragments
#Override
public void onResume(){
super.onResume();
SharedPreferences prefs =
getActivity().getSharedPreferences("message", Context.MODE_PRIVATE);
{
//this block is used for offsreen fragment, it will get update, when it go to forescreen
boolean sayHello = prefs.getBoolean("say_hello", false);
if(sayHello){
locationTextView =
(TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}else{
// say something elese
}
}
{
//this listener is for forescreen fragment, as soon as shared preferences will be updated,
// listerner willbe called and you can update your view depending on changed parameters
prefs.registerOnSharedPreferenceChangeListener(
new OnSharedPreferenceChangeListener(){
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key
){
if(key.equals("say_hello")){
boolean sayHello = sharedPreferences.getBoolean("say_hello", false);
if(sayHello){
locationTextView =
(TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}else{
// say something elese
}
}
}
}
);
}
}
You also can use Otto bus it is still unsutable for activity to fragment communication, as fragment can be in !isResumed state, but it is usefull fro fragment -activity comunication.
If you need some complex state tracking for each fragment and activity separatly, I'd recomment to use sqlDatabase and CursorLoaders. It will give you good controll over states and instan comunication.
Edit:
Its not that you cannot pass view from fragment to activity with getters.
Problem - you cannot garanty, that you completly aware of state of the fragment and a view. You try to update views on onStart of activity, which is call earlier, then fragmentsonStart, because fragment have to be generated by adapter and go through attachement process. (to find yout if fragment is attached to activity, you have to set listener in activity and call it ononActivityAttached` of fragment. See android studio activity with fragment template). Thus, when you call to change views, fragment and views probably did not exist.
Futhermore you should read about fragment and activity lifecycle and read about context ( espesialy why strong referencing views in unrelated context holder lead to sever memmory leaks and lificle errors

Creating DialogFragment with EditText

I'm new to android, started it about a month ago, and now I'm trying to make a "Shopping List" app for the sake of practice. In this app I have a ListView, where user can insert items via EditText above that ListView. When user longClick on item, ContextMenu with "Edit", "Delete" and "Mark" fields appears. I have already made "Delete" button work, but I still have problems with "Edit" function. To make this function work I created DialogFragment class, so when user presses the "Edit" button, this DialogFragment appears. This DF has EditText field, where we enter data we want to change. Here is DialogFragment class code:
public class AlertEdit extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder bd = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
bd.setView(inflater.inflate(R.layout.alert, null))
.setTitle("Edit")
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doNegativeClick();
}
});
return bd.create();
}
as you can see, we have positive button here, which calls doPositiveClick method from MyActivity, which appears to be the main activity.
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
So, here is the MyActivity class code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
lw = (ListView) findViewById(R.id.listView);
edtxt = (EditText) findViewById(R.id.editText);
alertEd = (EditText) findViewById(R.id.alertEdit);
goods = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, goods);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v,
int position, long id) {
}
});
registerForContextMenu(lw);
edtxt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
goods.add(0, edtxt.getText().toString());
adapter.notifyDataSetChanged();
edtxt.setText("");
return true;
}
}
return false;
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo info){
super.onCreateContextMenu(menu, v, info);
getMenuInflater().inflate(R.menu.actions, menu);
}
public boolean onContextItemSelected(MenuItem item) {
position = (int) info.id;
switch (item.getItemId()) {
case R.id.cnt_mnu_delete:
goods.remove(position);
adapter.notifyDataSetChanged();
return true;
case R.id.cnt_mnu_edit:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doPositiveClick()
{
}
public void doNegativeClick()
{
}
public void showDialog()
{
DialogFragment frag = new AlertEdit();
frag.show(getFragmentManager(), "edit");
}
}
My problem is that I have no idea how to create that Edit function. I tryied to use AdapterContextMenuInfo, but it works only in onContextItemSelected method, because it requires and Item to work with. Hope you help me and sorry for the possible lack of information, ask me any additional questions please.
P.S. I'm trying to make this dialog for almost two weeks already and I'm really frustrated because of that.
I'm using this method - it's simple and you may adapt it to your needs:
First of all make an interface to handle your result, for example:
public interface OnDialogResultListener {
public void onDialogResult(String result);
}
Then use your dialog with additional view, like this:
public void showDialogAndGetResult(final int title, final String message, final String initialText, final OnDialogResultListener listener) {
// additional View - use appropriate View to your needs:
final EditText editText = new EditText(this);
editText.setText(initialText);
new AlertDialog.Builder(MainActivity.this)//
.setTitle(title)//
.setMessage(message)//
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onDialogResult(editText.getText().toString());
}
}
})//
.setNegativeButton(android.R.string.cancel, null)//
.setView(editText)//
.show();
}
At last implement this interface in your activity:
public class YourActivity Extends Activity implements OnDialogResultListener{
...
#Override
public void onDialogResult(String result) {
//do what you need
}
...
}
Edit:
You may replace EditText by any View, including Layouts.
Still you may use the same scheme to return result from your DialogFragment descendant - just pass OnDialogResultListener in constructor or initializing method. I would say AlertDialog is more lightweight and DialogFragment allows more control and you may use both according to your needs.

Decimal to Binary is not working

I know for a fact I'm missing something extremely small but i can not seem to get my code to compile without errors. I am attempting to get the text field to take in a decimal number and OnClick, it will spit out the numbers binary equivalent.
It keeps telling me to initialize Binary but if i set it to 0, that makes Binary '0' instead of converting the decimal number.
Any help will would great! This is is my MainActivity.java file:
public class MainActivity extends ActionBarActivity {
#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();
}
final EditText editDecimal = (EditText) findViewById(R.id.editDecimal);
final EditText editBinary = (EditText) findViewById(R.id.editBinary);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int decimal = Integer.valueOf(editDecimal.getText().toString());
int binary;
editBinary.setText(Integer.toBinaryString(binary));
}
});
}
#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;
}
}
}
You don't need the variable binary. Instead you just need to do this:
editBinary.setText(Integer.toBinaryString(decimal));

Radio Group as Circular Page Indicator

I am trying to use RadioGroup as a CircularPageIndicator. The problem is with the RadioGroup.OnCheckedChangeListener. It seems to call it self when onPageSelected is called. However I want it to work vice versa i.e. when I select a radioButton it should change a view based on the location of the Array index being provided. However it seems as if onCheckedChange is never called when I change a check on the radio button and so onCheckedChange never triggers.
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener, OnPageChangeListener {
ViewPager mImagePager;
ImagePagerAdapter mPagerAdapter;
RadioGroup mPageIndicator;
boolean swipeChange = false;
int[] mRadioButtonIds = new int[] { R.id.radio0, R.id.radio1, R.id.radio2, R.id.radio3, R.id.radio4 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponents();
mPageIndicator.setOnCheckedChangeListener(this);
mImagePager.setAdapter(mPagerAdapter);
mImagePager.setOnPageChangeListener(this);
}
/**
*
*/
private void initComponents() {
mPageIndicator = (RadioGroup) findViewById(R.id.radioGroup1);
mImagePager = (ViewPager) findViewById(R.id.imgPager);
mPagerAdapter = new ImagePagerAdapter();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int pSelectedPagePosition) {
swipeChange = true;
mPageIndicator.check(mRadioButtonIds[pSelectedPagePosition]);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (!swipeChange) {
int itemPosition = Arrays.asList(mRadioButtonIds).indexOf(checkedId);
mImagePager.setCurrentItem(itemPosition, true);
swipeChange = false;
}
}
}
Note : I don't want to use any third party code/lib to create a custom Circular Page Indicator.
Can any one please point a mistake here. Is there a reason for the RadioGroup not to work?
I forgot to take a look at the documentation!
http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Why is my android.R.id.home not called in my fragment?

I'm currently using FragmentStatePagerAdapter and I would like it to have a "navigate up" feature (DisplayHomeAsUpEnabled). When I set the following code it shows up as a correct navigate back button. But nothing happens when I click on it, can you guys see anything that I', doing wrong in my code, I get no error while pressing the "navigate up" button and I get no compiler errors.
Here is the code, its in the "public boolean onOptionsItemSelected(MenuItem item) {" it gets interesting at the bottom.
public class ShareholdingDetailFragment extends FragmentActivity {
final int NUM_ITEMS = Portfolio.getPortfolio().count();
MyAdapter mAdapter;
ViewPager mPager;
Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(NUM_ITEMS + "e");
super.onCreate(savedInstanceState);
setContentView(R.layout.shareholdingdetailview_fragment_wrapper);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
public int getCount() {
return NUM_ITEMS;
}
public Fragment getItem(int position) {
return ShareholdingFragment.newInstance(position);
}
}
public static class ShareholdingFragment extends Fragment {
int mNum;
static ShareholdingFragment newInstance(int num) {
ShareholdingFragment f = new ShareholdingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#SuppressLint({ "NewApi", "NewApi" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shareholdingdetailview_fragment, container, false);
/****************Setting the Display as home and it shows*******************/
ActionBar bar = getActivity().getActionBar();
bar.setDisplayHomeAsUpEnabled(true);
/**********************************/
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home://Not working
System.out.println("test");//This isn't printed out
Intent upIntent = new Intent(getActivity(), DetailShareHoldingActivity.class);
if (NavUtils.shouldUpRecreateTask(getActivity(), upIntent)) {
getActivity().finish();
} else {
NavUtils.navigateUpTo(getActivity(), upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Try adding: setHasOptionsMenu(true); in your onCreate() in ShareholdingFragment.
Add setHomeButtonEnabled(true) on API Level 14 and higher when you configure your action bar. On API Level 11-13, the home button is enabled automatically.
If you're using the new Toolbar and ActionbarDrawerToggle. You can assign clickHandler directly. For my activities that have this drawer toolbar I implemented an interface to enable drawer if at root,
#Override
public void enableDrawer(boolean enable) {
mDrawerToggle.setDrawerIndicatorEnabled(enable);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Pop fragment back stack or pass in a custom click handler from the fragment.
}
});
}

Categories

Resources