Android Actionbar shows no items - android

I'm new to android and have this problem for while: No item appear on action bar, as you can see in the image below:
Here is my menu_main.xml:
<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="com.myappshop.myapp.MainActivity">
<item
android:id="#+id/action_favorite"
android:icon="#drawable/share_icon"
android:title="#string/share"
app:showAsAction="always"/>
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="ifRoom" />
</menu>
And the MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
EditText mEditTextWord;
EditText mEditTextDefinition;
DictionaryDatabase mDB;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDB = new DictionaryDatabase(this);
mEditTextWord = (EditText)findViewById(R.id.editTextWord);
mEditTextDefinition = (EditText)findViewById(R.id.editTextDefinition);
Button buttonAddUpdate = (Button)findViewById(R.id.buttonAddUpdate);
buttonAddUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
saveRecord();
}
});
mListView = (ListView)findViewById(R.id.listView);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
Log.d(TAG, "the id is logged " + Long.toString(id));
String nextId = String.valueOf(id+1);
Intent intent = new Intent(view.getContext(),DetailActivity.class);
intent.putExtra("key" ,mDB.getWord(id)+"");
intent.putExtra("value",mDB.getDefinition(id)+"");
intent.putExtra("nextId",nextId+"");
startActivity(intent);
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this,
"Records deleted = " + mDB.deleteRecord(id),
Toast.LENGTH_SHORT).show();
updateWordList();
return true;
}
});
updateWordList();
}
private void saveRecord() {
mDB.saveRecord(mEditTextWord.getText().toString(),
mEditTextDefinition.getText().toString());
mEditTextWord.setText("");
mEditTextDefinition.setText("");
updateWordList();
}
private void updateWordList() {
SimpleCursorAdapter simpleCursorAdapter = new
SimpleCursorAdapter( this,
android.R.layout.simple_list_item_1,
mDB.getWordList(),
new String[]{"word"},
new int[]{android.R.id.text1},
0);
mListView.setAdapter(simpleCursorAdapter);
}
#Override //added following https://stackoverflow.com/a/27192897/5774375
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.myappshop.myapp.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
The minimum API that I'v set is 15.
I've looked at similar answers on SO, like this but none resolve my probelm. So appreciate your help.
UPDATE: DetailActivity.java added:
public class DetailActivity extends AppCompatActivity {
private static final String TAG = DetailActivity.class.getSimpleName();
Button shareBtn, nextBtn, prevBtn, indexBtn ;
DictionaryDatabase mDB;
TextView title, body; //Globally Declaration
String nextId;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try{
String key = getIntent().getStringExtra("key");
String value = getIntent().getStringExtra("value");
String idString = getIntent().getStringExtra("nextId");
id = Integer.parseInt(idString) + 1; //to be used to rener the next item
title = (TextView) findViewById(R.id.title);
title.setText(key);
body = (TextView) findViewById(R.id.body);
body.setText(value);
}
catch(Exception e){
e.printStackTrace();
}
final Button button = (Button) findViewById(R.id.shareBtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
shareBtn = (Button) findViewById(R.id.shareBtn);
//render the next word
mDB = new DictionaryDatabase(this);
nextBtn = (Button) findViewById(R.id.nextBtn);
prevBtn = (Button) findViewById(R.id.prevBtn);
indexBtn = (Button) findViewById(R.id.indexBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id+=1;
Log.d(TAG, "the next item to be fetched has id: " + Long.toString(id));
Log.d(TAG, "return value is: " + mDB.getWord(id));
if (mDB.getWord(id) != "") {
String key = mDB.getWord(id);
String value = mDB.getDefinition(id);
title = (TextView) findViewById(R.id.title);
title.setText(key);
body = (TextView) findViewById(R.id.body);
body.setText(value);
prevBtn.setVisibility(View.VISIBLE);
} else {
finish();
}
}
});
prevBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
id-=1;
if (mDB.getWord(id) != "") {
String key = mDB.getWord(id);
String value = mDB.getDefinition(id);
title = (TextView) findViewById(R.id.title);
title.setText(key);
body = (TextView) findViewById(R.id.body);
body.setText(value);
nextBtn.setVisibility(View.VISIBLE);
} else {
finish();
}
}
});
indexBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#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()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}

You have to inflate your menu.xml before you can call its menu items. Add this before onOptionsItemSelected()
#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;
}
Sorry about that. I also noticed that you didn't declare your toolbar in your activitys' onCreate(). You would have to declare your toolbar before placing menu items on it. Add this to your activity's onCreate method.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Also, make sure you include your toolbar/appbar layout in your main layout for this activity.

Related

How to highlight the imagebutton when it is pressed

I want my imagebutton to hightlight it self, as the normal glow effect when a "normal" button is pressed. So i tried to put the image in, but then there is a "gray field" in the back of the image so i made it transparent so only the image will show but then the glow effect disappeared. Is there a solution to this? :)
please see imgur image as a example- Example image here
if it is to "hard" I can live with the gray field behind the image but is it possible then to make it green with the same highlight effect?
Should i put the code in MainActivity or my fragment java?
Fragment java
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
//TextView nya;
//TextView nsp;
TextView tstnr;
#SuppressWarnings("ResourceType")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
return inflater.inflate(R.layout.first_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
view = getActivity().findViewById(R.id.content_frame);
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
//nsp = (TextView) view.findViewById(R.id.nummertestsp);
// tstnr = (TextView) view.findViewById(R.id.numretladd);
// view = getActivity().findViewById(R.id.content_frame);
taframnummer.setVisibility(INVISIBLE);
msgTxt.setVisibility(INVISIBLE);
aonTxt.setVisibility(INVISIBLE);
aoffTxt.setVisibility(INVISIBLE);
rela1txt.setVisibility(INVISIBLE);
rela2txt.setVisibility(INVISIBLE);
sendSMSaoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgrela2);
}
}
);
// return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
Here my MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
else if (id == R.id.nav_share) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://hellmertz.se"));
startActivity(browserIntent);
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Put the imageView that you want to highlight above a View with bright color and set the visibility of the view equal to View.GONE. Now with your ImageButton
((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
myView.setVisibility(View.VISIBLE);
break;
}
case MotionEvent.ACTION_UP:
myView.setVisibility(View.GONE);
break;
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
myView.setVisibility(View.GONE);
break;
}
}
return true;
}
});
You can user selector drawable and have 3 different button drawables for each state. Create these file is drawables folder and add this line to button android:background="#drawable/button_selector"
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="#drawable/camera_button_hold" android:state_pressed="true"/>
<!-- focused -->
<item android:drawable="#drawable/camera_button_hold" android:state_focused="true"/>
<!-- default -->
<item android:drawable="#drawable/camera_button_normal"/>
</selector>
camera_button_hold.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#673ab7"/>
</shape>
camera_button_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="#673ab7"/>
</shape>

App crashes on orientation change in android

My application crashes when I flip orientation. If the commented out line in onCreate runs I can't flip orientation at all. without it I can flip but can't change my background image but when it flips back it still crashes.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private DrawerLayout mDrawerLayout;
private ListView mListView;
private ImageView bgimage;
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Toast.makeText(this, "made it", Toast.LENGTH_SHORT).show();
int n = savedInstanceState.getInt("imageId");
Toast.makeText(this, ""+n, Toast.LENGTH_SHORT).show();
bgimage = (ImageView) findViewById(R.id.imgOne);
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
Toast.makeText(this, ""+drwables.length, Toast.LENGTH_SHORT).show();
//This code here
//bgimage.setImageResource(drwables[n]);
}
else{
bgimage = (ImageView) findViewById(R.id.imgOne);
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mListView = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
String[] names = getResources().getStringArray(R.array.bandImages);
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this, R.layout.nav_list_row, R.id.textView, names);
mListView.setAdapter(itemsAdapter);
mListView.setOnItemClickListener(this);
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, (Toolbar) findViewById(R.id.toolbar), R.string.open, R.string.closed) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu();
}
public void onDrawerOpened(View view) {
super.onDrawerOpened(view);
getSupportActionBar().setTitle(getTitle());
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(toggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle.syncState();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
int n = Integer.parseInt(bgimage.getTag().toString());
savedInstanceState.putInt("imageId", n);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mListView);
menu.findItem(R.id.action_about).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#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 void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bgimage = (ImageView) findViewById(R.id.imgOne);
bgimage.setImageResource(drwables[position]);
bgimage.setTag(position);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(R.id.action_about == id){
Toast.makeText(this, "Lab 2 Spring 2016, Zack G Johnson", Toast.LENGTH_SHORT).show();
return true;
}
else{
return super.onOptionsItemSelected(item);
}
}
}
Try to place setContentView method before finding and using layout elements.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//put it here
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
Toast.makeText(this, "made it", Toast.LENGTH_SHORT).show();
int n = savedInstanceState.getInt("imageId");
Toast.makeText(this, ""+n, Toast.LENGTH_SHORT).show();
bgimage = (ImageView) findViewById(R.id.imgOne);
int[] drwables = {R.drawable.cindy, R.drawable.fred, R.drawable.kate, R.drawable.keith, R.drawable.matt, R.drawable.rickey};
Toast.makeText(this, ""+drwables.length, Toast.LENGTH_SHORT).show();
//This code here
//bgimage.setImageResource(drwables[n]);
}
else{
bgimage = (ImageView) findViewById(R.id.imgOne);
}
...

How to inflate badge counter in MenuItem using custom LayerDrawable

I was following this article. Unfortunatelly, badge isn't drawn. Of course I changed invalidateOptionsMenu method to supportInvalidateOptionsMenu method.
I was checking the log, step by step and found out that draw method in custom Drawable named BadgeDrawable is never called. Why is that?
I'm trying to use it in AppCompatActivity using Support Design Library version 23.0.1
I saw this answer but it seems to be out of date.
Is there anyone who managed to implement badger counter for MenuItem icon inside android.support.v7.widget.Toolbar?
If the way shown in the article is wrong then could you suggest other way to achieve the result as in example below?:
Here is a setup inside my application:
LayerDrawable XML ic_filter_notifications.xml:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/ic_filter_notification"
android:drawable="#drawable/ic_filter_grey600_18dp"
android:gravity="center"/>
<!-- set a place holder Drawable so android:drawable isn't null -->
<item android:id="#+id/ic_filter_badge"
android:drawable="#drawable/ic_filter_grey600_18dp">
</item>
</layer-list>
Menu that I use in the Toolbar menu_activity_main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cobytu="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/menu_settings"
android:orderInCategory="100"
android:title="#string/menu_settings"
cobytu:showAsAction="never"/>
<item
android:id="#+id/menu_logout"
android:orderInCategory="1000000"
android:title="#string/menu_logout"
cobytu:showAsAction="never"/>
<item
android:id="#+id/action_filter"
android:title="#string/filters"
android:icon="#drawable/ic_filter_notifications"
cobytu:showAsAction="always"/>
<item
android:id="#+id/action_location"
android:icon="#drawable/ic_map_marker_radius_grey600_18dp"
android:title="#string/location"
cobytu:showAsAction="always"/>
</menu>
This is function sets the count int for new BadgeDrawable inside UsefulFunctions class - UsefulFunctions.java:
public class UsefulFunctions {
private Context ctx;
public UsefulFunctions(Context context){
ctx = context;
}
public static void setBadgeCount(Context context, LayerDrawable icon,
int count) {
BadgeDrawable badge;
// Reuse drawable if possible
Drawable reuse = icon.findDrawableByLayerId(R.id.ic_filter_badge);
if (reuse != null && reuse instanceof BadgeDrawable) {
badge = (BadgeDrawable) reuse;
} else {
Log.d("mTAG", UsefulFunctions.class.getName()
+ " I'm creating new BadgeDrawable!");
badge = new BadgeDrawable(context);
}
badge.setCount(count);
icon.mutate();
Log.d("mTAG",
UsefulFunctions.class.getName() + " badge: " + badge.toString()
+ " count: " + count);
icon.setDrawableByLayerId(R.id.ic_filter_badge, badge);
}
}
This is the important scrap of my MainActivity where I invoke BadgeDrawable creation. I also show what's inside onCreate and in onOptionsItemSelected, may be needed - MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DialogFragmentFilters.FiltersRefreshInterface{
public String username;
//CollapsingToolbarLayout
private CollapsingToolbarLayout mCollapsingToolbarLayout;
//Toolbar
private Toolbar mToolbar;
//TabLayout
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
//NavigationDraver
private static final String SELECTED_ITEM_ID = "selected_item_id";
private static final String FIRST_TIME = "first_time";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavigationView mNavigationView;
private int mSelectedId;
private boolean mUserSawDrawer = false;
private TextView mNavHeaderNameText;
private TextView mNavHeaderEmailText;
private DatabaseHandler db;
private UserFunctions userFunctions;
private AlertDialog.Builder dialogBuilder;
private AlertDialog alertDialog;
private JSONObject jsonLocation = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFunctions = new UserFunctions();
db = new DatabaseHandler(getApplicationContext());
username = db.getUserDetails().get(DatabaseHandler.getKEY_USER_LOGIN());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setupToolbar();
setupTablayout();
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
View header = LayoutInflater.from(MainActivity.this).inflate(R.layout.nav_header, null);
mNavHeaderNameText = (TextView) header.findViewById(R.id.tv_nav_header_name);
mNavHeaderNameText.setText("Siema "+username+"!");
mNavHeaderEmailText = (TextView) header.findViewById(R.id.tv_nav_header_email);
mNavHeaderEmailText.setText(db.getUserDetails().get(DatabaseHandler.getKEY_USER_EMAIL()));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (!didUserSeeDrawer()) {
showDrawer();
markDrawerSeen();
} else {
hideDrawer();
}
mSelectedId = savedInstanceState == null ? R.id.navigation_item_4 : savedInstanceState.getInt(SELECTED_ITEM_ID);
navigate(mSelectedId);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(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();
showActionDialog(id);
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.menu_settings:
return true;
case R.id.menu_logout:
dialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(
MainActivity.this, R.style.Theme_AppCompat_Light_Dialog));
dialogBuilder
.setTitle(getResources().getString(R.string.logoutAlertTitle))
.setIcon(R.drawable.ic_logout).setMessage(getResources().getString(R.string.logoutAlertMessage)).setPositiveButton(getResources().getString(R.string.logoutAlertYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
((RelativeLayout) findViewById(R.id.fl_mainContent))
.animate()
.alpha(0f)
.setListener(
new AnimatorListenerAdapter() {
public void onAnimationEnd(
Animator animation) {
mDrawerLayout
.setVisibility(View.INVISIBLE);
mDrawerLayout
.setAlpha(1f);
mDrawerLayout
.animate()
.setListener(null);
}
});
userFunctions.logoutUser(getApplicationContext());
Intent i = new Intent(MainActivity.this, LoginActivity.class);
// MainActivity.this.deleteDatabase("cobytu_db");
startActivity(i);
finish();
}
})
.setNegativeButton(getResources().getString(R.string.logoutAlertNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog = dialogBuilder.create();
alertDialog.show();
return true;
}
return false;
}
public int filterCounter = 0;
class FetchCountTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
// example count. This is where you'd
// query your data store for the actual count.
return 5;
}
#Override
public void onPostExecute(Integer count) {
setNotifCount(count);
}
}
private void setNotifCount(int count){
filterCounter = count;
supportInvalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
MenuItem item = menu.findItem(R.id.action_filter);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// Update LayerDrawable's BadgeDrawable
Log.d("mTag", "onCreateOptionsMenu: this: " + this.toString());
UsefulFunctions.setBadgeCount(this, icon, filterCounter);
return true;
}
#Override
public void onRefreshFilters(int counter) {
setupTablayout();
Toast.makeText(MainActivity.this, "List has been refreshed! " + counter, Toast.LENGTH_SHORT).show();
filterCounter = counter;
new FetchCountTask.execute();
}
}

How to make click on ActionBar Logo in android

I tried to do something on Click on icon in ActionBar but do nothing.I also like to do open drawer_layout on click on a icon in action bar. How to make it clickable and handle the event of it`s pressing?
public class MainActivity extends AppCompatActivity {
ViewPager viewPager,viewPager01;
CustomSwipAdapter swip_adapter;
CustomSwipAdapter01 swip_adapter01;
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
getSupportActionBar().setLogo(R.drawable.sample_01);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("");
}
catch (Exception e) {
}
viewPager = (ViewPager)findViewById(R.id.viewpager);
swip_adapter =new CustomSwipAdapter(this);
viewPager.setAdapter(swip_adapter);
/* viewPager01 = (ViewPager)findViewById(R.id.viewpager01);
swip_adapter01 =new CustomSwipAdapter01(this);
viewPager01.setAdapter(swip_adapter01);*/
menu = new String[]{"Home","E-Gift Voucher"};
dLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
dList = (ListView)findViewById(R.id.left_drawer);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);
dList.setAdapter(adapter);
dList.setSelector(android.R.color.holo_blue_dark);
dList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
}
});
}
#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);
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.main_activity_action,menu);
return super.onCreateOptionsMenu(menu);*/
MenuInflater inf = getMenuInflater();
inf.inflate(R.menu.main_activity_action,menu);
return true;//super.onCreateOptionsMenu(menu);
}
#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();
switch (item.getItemId()){
case android.R.id.home:
Toast.makeText(MainActivity.this,"Click on Logo",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
layout xml
<RelativeLayout
android:id="#+id/rl_main_search_layout"
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:background="#color/transparent_semi"
tools:context="com.worldofmoms.views.fragments.search_and_explore.SearchFragment">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ActionBar_Light"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar_search"
android:background="#android:color/white"
android:visibility="gone"
/>
</RelativeLayout>
Add in your activity onCreate()
mToolbar = (Toolbar) view.findViewById(R.id.toolbar_search);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and Add
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==android.R.id.home){
// home button from toolbar clicked
}
}
Add in your activity onCreate(): i am quite sure it may help you...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Custom code for image icon which redirects to homepage
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
webViewPlaceholder.loadUrl("http://www.salebhai.com");
} });
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.LEFT
| Gravity.CENTER_VERTICAL);
layoutParams.leftMargin = 20;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
actionBar.setDisplayHomeAsUpEnabled(true);
Thank you ,
happy Coding.....

Actionbar button not showing in searchview android

I have a searchview and a button i my actionbar,but the button gets displayed only in the landscape mode and however I try it wont get displayed in the portrait mode.
Landscape Mode
Portrait Mode
this is my menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_item_search"
android:title="Search"
android:showAsAction="ifRoom"
android:icon="#android:drawable/ic_menu_search"
android:actionViewClass="android.widget.SearchView" />
<item
android:id="#+id/submit"
android:title="submit"
android:showAsAction="always" />
</menu>
This is my main activity
public class Myclass extends Activity implements OnQueryTextListener,OnItemClickListener {
GroupAdapter grpAdapter;
public static ArrayList<GroupsModel> arrayOfList;
public static ListView listView;
public static String base_url = "myurl";
private SeekBar volumeControl = null;
private TextView year;
private int progressChanged = 0;
private Menu menu_data;
MenuItem submitBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two);
ActionBar actionBar = getActionBar();
//actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
volumeControl = (SeekBar) findViewById(R.id.volume_bar);
year = (TextView)findViewById(R.id.year_level);
volumeControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
progressChanged = progress;
year.setText(Integer.toString(progressChanged+7));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
arrayOfList = new ArrayList<GroupsModel>();
listView = (ListView) findViewById(R.id.group_listview);
listView.setOnItemClickListener(this);
listView.setTextFilterEnabled(true);
new ProgressTask(two.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
#SuppressWarnings("unused")
private two activity;
public ProgressTask(two two) {
this.activity = two;
context = two;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
protected Boolean doInBackground(final String... args) {
//arrayOfList = new ArrayList<GroupsModel>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("",""));
JSONParser jp = new JSONParser();
JSONArray groups_obj = jp.makeHttpRequest(base_url + "groups/all", "GET", params);
for (int i = 0; i < groups_obj.length(); i++) {
GroupsModel group = new GroupsModel();
try {
JSONObject grp = groups_obj.getJSONObject(i);
group.setGroupId(grp.getInt("id"));
group.setGroupname(grp.getString("name"));
arrayOfList.add(group);
}
catch (JSONException e) {
e.printStackTrace();
}
}
two.this.runOnUiThread(new Runnable() {
#Override
public void run() {
grpAdapter = new GroupAdapter(two.this, R.layout.two_row,arrayOfList);
listView.setAdapter(grpAdapter);
}
});
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu_data = menu;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setSubmitButtonEnabled(false);
searchView.setOnQueryTextListener(this);
searchView.setQueryHint("My text");
searchView.setIconifiedByDefault(false);
submitBtn = (MenuItem)menu_data.findItem(R.id.submit);
submitBtn.setIcon(R.drawable.button22);
submitBtn.setEnabled(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.submit:
if(submitBtn.isVisible())
Toast.makeText(getApplicationContext(), Integer.toString(progressChanged+7),Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
if (TextUtils.isEmpty(newText))
{
listView.clearTextFilter();
}
grpAdapter.getFilter().filter(newText.toString());
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// TODO Auto-generated method stub
submitBtn.setIcon(R.drawable.button111);
submitBtn.setEnabled(true);
for (GroupsModel s : arrayOfList)
s.setChecked(false);
final boolean isChecked = GroupAdapter.items.get(position).getChecked();
if(isChecked==false){
GroupAdapter.items.get(position).setChecked(!isChecked);
grpAdapter.notifyDataSetChanged();
}
else{
GroupAdapter.items.get(position).setChecked(isChecked);
grpAdapter.notifyDataSetChanged();
}
} }
Please help me.
If it doesn't concern you that the SearchView is collapsed at the start, try configuring the SearchView like this:
android:showAsAction="collapseActionView|ifRoom"
This should make the actionbar show both, the SearchView and your Button. Plus the SearchView will only take up the remaining space to the left, when it gets expanded.
According to developer.android.com
If your app is using the Support Library for compatibility on versions as low as Android 2.1, the showAsAction attribute is not available from the android: namespace. Instead this attribute is provided by the Support Library and you must define your own XML namespace and use that namespace as the attribute prefix. (A custom XML namespace should be based on your app name, but it can be any name you want and is only accessible within the scope of the file in which you declare it.) For example:
res/menu/main_activity_actions.xml >>>>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
yourapp:showAsAction="ifRoom" />
...
</menu>
A SearchView will default to taking up a majority of, if not all of the action bar in portrait mode. Try decreasing the size of the SearchView in menu.xml and see if the button is displayed.

Categories

Resources