Action bar Action View won't work - java

I am trying to make a collapsible EditText in the Action Bar. I have followed the Android Developers guide. But when I click on my search icon, nothing happens.
What can I do?
Here is my code.
The activity:
public class ElementPagerActivity extends ActionBarActivity
implements ElementListFragment.onElementClickListener,
CalculateFragment.OnCalculateClickListener{
ViewPager theViewPager;
private ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = getSupportActionBar();
theViewPager = new ViewPager(this);
theViewPager.setId(0x1);
theViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
if(position == 0){
return new ElementListFragment();
} return Element.values()[position - 1].toFragment();
}
#Override
public int getCount() {
return Element.values().length + 1;
}
});
theViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
if(position == 0){
actionBar.setTitle(R.string.Element_info_activity_label);
actionBar.selectTab(null);
} else {
actionBar.setTitle(Element.values()[position - 1].getName());
actionBar.selectTab(actionBar.getTabAt(position - 1));
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
actionBar = actionBar;
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
int position = tab.getPosition();
theViewPager.setCurrentItem(position + 1, true);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
int position = tab.getPosition();
theViewPager.setCurrentItem(position + 1, true);
}
};
for (int i = 0; i < Element.values().length; i++){
actionBar.addTab(
actionBar.newTab()
.setText(Element.values()[i].getName())
.setTabListener(tabListener));
}
theViewPager.setCurrentItem(0);
actionBar.selectTab(null);
setContentView(theViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.element_pager, menu);
menu.findItem(R.id.pager_activity_show_list_action).setVisible(!(theViewPager.getCurrentItem() == 0));
menu.findItem(R.id.pager_activity_edit_text_action).expandActionView();
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.pager_activity_show_list_action){
theViewPager.setCurrentItem(0, true);
return true;
} else if (id == R.id.pager_activity_edit_text_action){
return false;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (theViewPager.getCurrentItem() == 0){
super.onBackPressed();
} else {
theViewPager.setCurrentItem(0);
}
}
#Override
public void onElementClick(int position) {
theViewPager.setCurrentItem(position + 1, true);
}
#Override
public Element onRequestElement() {
return Element.values()[theViewPager.getCurrentItem() - 1];
}
}
Menu resources:
<menu 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"
tools:context=".MainActivity" >
<item android:id="#+id/pager_activity_edit_text_action"
app:showAsAction="always|collapseActionView"
android:title="text here"
android:icon="#android:drawable/ic_menu_search"
android:actionLayout="#layout/test"/>
<item android:id="#+id/pager_activity_show_list_action"
android:title="#string/action_bar_pager_show_list"
android:orderInCategory="100"
app:showAsAction="ifRoom|withText" />
</menu>
Action layout (test.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="element"
android:inputType="textCapWords"/>
</LinearLayout>
And here is a short film demonstrating the problem.
I appreciate all answers.
Greetings from the Netherlands

You can use a SearchView, which will make things a bit easier for you.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/search"
android:title="#string/search_title"
android:icon="#drawable/ic_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
</menu>
more here: http://developer.android.com/training/search/setup.html

Related

Menu item click in a navigation drawer intent to activity hosting a fragment

Disclaimer: This is the first app I am building so I am learning the hard way to use fragments first, so my code is all over the place.
I have menu items inside a navigation view that loads fine however the menu item clicks don't work. It doesn't crash it just stares at me. I would like to use an intent to display a fragment and I am lost from changing and trying so many different options.
XML FOR NAV DRAWER & MENU ITEMS:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_pageone"
android:background="#drawable/rygg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarThumbVertical="#color/primary_dark_color"
tools:openDrawer="start"
tools:context="com.android.nohiccupsbeta.pageone">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.NavigationView
android:id="#+id/navigation_header_container"
app:headerLayout="#layout/header"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:itemIconTint="#color/category_vodka"
app:itemTextColor="#color/primary_dark_color"
app:menu="#menu/drawermenu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
JAVA:
public class pageone extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pageone);
setupDrawer();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawermenu, menu);
return true;
}
/**
*
* #param item For the hamburger button
* #return
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.itemWhiskey:
Intent whiskeyIntent = new Intent(pageone.this, whiskeyActivity.class);
startActivity(whiskeyIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Make sure the drawer open and closes in sync with UI visual
* #param savedInstanceState
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mToggle.syncState();
}
/**
* Function to make sure all the drawer open & closes properly
*/
public void setupDrawer() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_closed) {
#Override
public void onDrawerClosed(View closeView) {
Toast.makeText(pageone.this, "Happy You Learned", Toast.LENGTH_SHORT).show();
super.onDrawerClosed(closeView);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View openView) {
Toast.makeText(pageone.this, "Effects Of Alcohol", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(openView);
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(mToggle);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
XML FOR FRAGMENT:
<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"
android:orientation="vertical"
android:id="#+id/frame_container2"
tools:context="com.android.nohiccupsbeta.WhiskeyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/frag_whiskey_skin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:textColor="#000000"
android:textSize="16sp" />
<ImageButton
android:id="#+id/expand_collapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:background="#android:color/transparent"
android:src="#drawable/ic_expand_more"
android:padding="16dp"/>
</FrameLayout>
JAVA:
public class WhiskeyFragment extends Fragment {
private TextView mWhiskeySkin;
#Override
public void onViewCreated(View view, #Nullable Bundle SavedInstanceState) {
super.onViewCreated(view, SavedInstanceState);
getActivity().setTitle("WHISKEY EFFECTS");
mWhiskeySkin = (TextView) view.findViewById(R.id.frag_whiskey_skin);
mWhiskeySkin.setText(R.string.whiskey_skin);
hasOptionsMenu();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_whiskey, container, false);
hasOptionsMenu();
return v;
}
}
XML FOR SECOND ACTIVITY:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
public class whiskeyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whiskey);
}
public class Whiskeyed {
private String whiskeySkin;
private String whiskeyBrain;
public String getWhiskeySkin(){
return whiskeySkin;
}
public String getWhikeyBrain(){
return whiskeyBrain;
}
public void setWhiskeySkin(String whiskey_skin){
this.whiskeySkin = whiskey_skin;
}
public void setWhiskeyBrain(String whiskeyBrain) {
this.whiskeyBrain = whiskeyBrain;
}
}
}
try to change to content of your onNavigationItemSelected of your pageone.java
from here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
to here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone); // ID of your drawerLayout
int id = item.getItemId();
switch (id) {
case R.id.menu1: // Change this as your menuitem in menu.xml.
// Your fragment code goes here..
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
break;
case R.id.menu2: // Change this as your menuitem in menu.xml.
// or Your fragment code goes here...
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START, true);
return true;
}

Doesn't re-load fragments ViewPager

I have a problem with fragments and the ViewPager, my ViewPager is composed of five tabs, each one is a Fragment.
On the first load I don't have problem with these load, but when I open another fragment (Ahead the main), and go back to the main, the fragments where I was, and those, has been removed (invisible).
For fix that I need to "get away" for two pages before the central page loads.
Everything is only in API 21 (5.0.1), with Android Studio.
MainActivity.java:
public class MainActivity extends FragmentActivity {
private MainActivityFragment frag_MainActivity;
private CreditsFragment frag_Credits;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag_MainActivity = new MainActivityFragment(this);
frag_Credits = new CreditsFragment();
switchFrag("main");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_home) {
switchFrag("main");
return true;
} else if (id == R.id.action_credits) {
switchFrag("credits");
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchFrag(String view){
Fragment frag = new Fragment();
if(view.equals("main")){
getActionBar().show();
frag = new MainActivityFragment(this);
} else if(view.equals("credits")){
getActionBar().hide();
frag = new CreditsFragment();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, frag)
.addToBackStack(null).commit();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
switchFrag("main");
return true;
}
return super.onKeyUp(keyCode, event);
}
public void closeApp() {
finish();
System.exit(0);
}
And the XML (activity_main.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
MainActivityFragment.java:
public class MainActivityFragment extends Fragment implements ActionBar.TabListener {
private ViewPager viewPager;
private MyAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Lun", "Mar", "Merc", "Gio", "Ven"};
MainActivity main;
public MainActivityFragment(MainActivity instance) {
main = instance;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager) main.findViewById(R.id.pager);
actionBar = main.getActionBar();
mAdapter = new MyAdapter(main.getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(actionBar.getTabCount() == 0){
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {}
XML (fragment_settings.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"
tools:context=".MainActivityFragment">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
If the Adapter is needed, here it is:
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 5;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch(position){
case 0:
return new LunFragment();
case 1:
return new MarFragment();
case 2:
return new MerFragment();
case 3:
return new GioFragment();
case 4:
return new VenFragment();
}
return null;
}
}
Replace mAdapter = new MyAdapter(main.getSupportFragmentManager()); with mAdapter = new MyAdapter(main.getChildFragmentManager());. You need to create the fragments as inner fragments of your MainActivityFragment.

Unable to start activity. Caused by: android.view.InflateException:

LogCat Error:
https://github.com/Heromine/tempapp1/issues/2
Can anybody tell me, why I am getting this error?
I don't understand what i am doing wrong:
MainActivity.java:
public class MainActivity extends ActionBarActivity {
// UI elements
public static Toolbar toolbar;
public static ViewPager viewPager;
private AppSectionsPagerAdapter mAppSectionsPagerAdapter;
// Tab titles
private String[] tabs = {"Home", "Note"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if (firstRun) { // here run your first-time instructions, for example :
startActivity(new Intent(this, MyIntro.class));
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action/tool bar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); // Setting toolbar with setSupportActionBar()
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(mAppSectionsPagerAdapter);
/* ViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
swipeLayout.setEnabled(false);
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
swipeLayout.setEnabled(true);
break;
}
return false;
}
});
*/
// Adding Tabs
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
tabs.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections
// change toolbar title
if (position == 0)
toolbar.setTitle(getResources().getString(R.string.app_name));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent("android.intent.action.SettingsActivity"));
return true;
case R.id.action_donate:
startActivity(new Intent("android.intent.action.DonateActivity"));
return true;
case R.id.action_rate:
Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.service.beta.servicenotesbeta"));
startActivity(i2);
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i) {
switch (i) {
case 0:
return new Fragment_main();
case 1:
return new Fragment_second();
/*case 2:
return new Fragment_third();
case 3:
return new Fragment_fourth();*/
default:
return null;
}
}
#Override
public int getCount() {
return 2; //3-4
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/ToolBarStyle"
android:id="#+id/toolbar"/>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
</RelativeLayout>
</LinearLayout>
Please tell me what i am doing wrong
I put the issue link because when i put the issue code it gives me an error
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
at com.astuetz.PagerSlidingTabStrip.notifyDataSetChanged(PagerSlidingTabStrip.java:200)
at com.astuetz.PagerSlidingTabStrip.setViewPager(PagerSlidingTabStrip.java:182)
at com.service.beta.servicenotesbeta.MainActivity.onCreate(MainActivity.java:67)
there is a problem with <com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
have you looked at https://github.com/astuetz/PagerSlidingTabStrip/ for further infos?
Go to AppSectionsPagerAdapter.java and add this piece of code necessary to provide a title that your PagerSlidingTabStrip can obtain.
#Override
public CharSequence getPageTitle(int position) {
if (position == 0)
{
return "Movies";
}
if (position == 1)
{
return "Events";
}
return null;
}
I fixed, the problem was that i didn't add the titles to the tabs

Enable and disable search action in a tabbed activity

I have a tabbed activity with two tabs, and when I am in the second one I want to have a search action be shown in the actionbar. I do not want it to show in the first tab, only the second.
This is what I have for my LaunchActivity.java
public class LaunchActivity extends ActionBarActivity {
ViewPager pager;
int Numboftabs = 2;
boolean searchDisabled = false;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
searchDisabled = true;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_launch, menu);
return super.onCreateOptionsMenu(
}
...
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem search = menu.findItem(R.id.action_search);
if(searchDisabled) {
search.setEnabled(false);
}
super.onPrepareOptionsMenu(menu);
return true;
}
}
menu_launch.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".LaunchActivity">
<item android:id="#+id/action_search"
android:title="#string/action_search"
android:icon="#drawable/ic_action_search"
app:showAsAction="ifRoom" />
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
Does anyone know why this is not working? The search action shows up but doesn't hide when on the first tab.
Approach:
You can solve this by adding a class variable for the MenuItem.
MenuItem search;
Then in onPrepareOptionsMenu you only initialize it:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
search = menu.findItem(R.id.action_search);
super.onPrepareOptionsMenu(menu);
return true;
}
Then in your onPageChangeListener you do this to show/hide the search item:
#Override
public void onPageSelected(int position) {
if (position == 0) {
search.setEnabled(false);
search.setVisible(false);
} else {
search.setEnabled(true);
search.setVisible(true);
}
}
That should achieve what you want to do.
Approach:
Alternative better solution would be to set up the options menu in the fragment:
Add hasOptionsMenu(true) to your Fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
And set the visibility in onCreateOptionsMenu (also in the fragment!):
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
MenuItem search = menu.findItem(R.id.action_search);
search.setEnabled(false);
search.setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}

Custom SwitchPreference not saving value

When I access the PreferenceScreen, I notice that my custom switch is off. Then I turn it on and restart the app. I went back to the PreferenceScreen and the switch went back off. This doesn't happen when I use the default SwitchPreference. I am able to customize the SwitchPreference the way I want it to be, so the only problem is the switch value not saving. I have four files related to a customize SwitchPreference and all of the Preferences are placed in an extension of a PreferenceFragment
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings"
>
<com.example.CustomSwitchPreference
android:key="vibration"
android:title="vibration"
android:summary=""
android:defaultValue="true" />
</PreferenceScreen>
CustomSwitchPreference.java:
public class CustomSwitchPreference extends SwitchPreference {
public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSwitchPreference(Context context) {
super(context);
}
#Override
protected View onCreateView( ViewGroup parent )
{
LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
return li.inflate( R.layout.customswitch_preference, parent, false);
}
/*
#Override
protected void onBindView(View view) {
MainActivity mainActivity = (MainActivity)getContext();
RelativeLayout relativeLayout = (RelativeLayout)mainActivity.findViewById(R.id.switch_frame);
Switch s = (Switch)relativeLayout.getChildAt(1);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
persistBoolean(isChecked);
}
});
super.onBindView(view);
}
*/
}
customswitch_preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/switch_title"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_alignParentStart="true"/>
<Switch
android:id="#+id/switch_pref"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private ActionBar actionBar;
private boolean mInit = false;
private boolean showIcon = true;
private Menu m;
private GridFragment gridFragment;
private SettingsFragment settingsFragment;
public ImageButton startButton;
public TextView gameTimer;
public TextView mineCount;
public boolean isVibrating;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsFragment = new SettingsFragment();
actionBar = getActionBar();
actionBar.setTitle("Settings");
actionBar.setCustomView(R.layout.actionbar);
//actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
startButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
startButton.setImageResource(R.drawable.smiley2);
break;
case MotionEvent.ACTION_UP:
restartGame();
break;
}
return false;
}
});
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
TextView textView;
int[] resources =
{R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
for(int r: resources) {
textView = (TextView) findViewById(r);
textView.setTypeface(myTypeface);
}
if (findViewById(R.id.fragment_container) != null){
if (savedInstanceState != null) {
return;
}
}
}
public void restartGame() {
startButton.setImageResource(R.drawable.smiley);
getFragmentManager().beginTransaction().remove(gridFragment).commit();
setText(999, gameTimer);
startGame();
}
private void startGame(){
gridFragment = new GridFragment();
gridFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();
}
public void setText(int value, TextView textView){
value = Math.min(999,value);
value = Math.max(-99,value);
textView.setText(String.format("%03d",value));
}
#Override
protected void onStart() {
if (!mInit) {
mInit = true;
Database db = new Database(this);
db.deleteAllSessions();
db.close();
startGame();
}
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
m = menu;
return true;
}
private void openSettings(){
showIcon = false;
gridFragment.pauseTimer();
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(gridFragment);
ft.add(android.R.id.content, settingsFragment).commit();
//ft.replace(android.R.id.content,settingsFragment);
}
private void updateSettings(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Map<String, ?> map = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
isVibrating = (Boolean)map.get("vibration");
}
private void closeSettings(){
showIcon = true;
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.show(gridFragment);
ft.remove(settingsFragment).commit();
//ft.replace(android.R.id.content,gridFragment);
gridFragment.resumeTimer();
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
openSettings();
return true;
}
else if(id == R.id.backButton){
updateSettings();
closeSettings();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(showIcon);
item = menu.findItem(R.id.backButton);
item.setVisible(!showIcon);
return super.onPrepareOptionsMenu(menu);
}
}
You're never actually setting or saving the state of the switch. You need to override onBindView to set the initial state of the view, and attach a checked change listener to the Switch (R.id.switch_pref) to listen for changes and persist them into SharedPreferences (you can call persistBoolean to do that).

Categories

Resources