How to add action items from SherlockFragment - android

I want to add action items to actionbar sherlock from shelock fragment and need to implement the click listener also. I have used following code for the fragment activity.
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class MyTasksFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.mytask_fragment_layout, container, false);
return view;
}
#Override
public void onCreateOptionsMenu( Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.action_mytask, menu);
}
}
And follwing is the code of action_mytask.xml (ic_action_edit image is also in the drawable folder)
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/action_task"
android:icon="#drawable/ic_action_edit"
android:title="#string/add_task"
android:showAsAction="ifRoom" />
</menu>
The added icon is not coming to the ABS. Here is the image
I want to know
How to add action items for the actionbar sherlock from sherlock fragment ?
How to implement click listners for those activities ?
Please help,
Thank you

you should call setHasOptionsMenu(true); in onCreate and you should all call super.onCreateOptionsMenu(menu, inflater)

Override onCreate method and put setHasOptionsMenu(true); in it. It will tell the activity that fragment has it's own option menu. For click listener override onOptionsItemSelected method.

Related

why my menu icon not showing in toolbar, just show blank toolbar

i try to add icon menu in toolbar. but my icon not showing. here my code. only show blank header. can someone help me...
this fragment class
package com.example.bams.task.fragments;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.bams.task.R;
/**
* Created by jack on 19/02/2017.
*/
public class AddProjectFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_project, container,false);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//menu.clear();
inflater.inflate(R.menu.header, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
this is my custom toolbar layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/colorBgFragment"
android:fitsSystemWindows="true"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBgFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editText"/>
</LinearLayout>
</LinearLayout>
and my menu icon
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/backBtn"
android:icon="#drawable/ic_back_filled"
app:showAsAction="always"
android:title="back"/>
</menu>
can anyone tell me whats wrong with my code?
Try this:
public class AddProjectFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_project, container,false);
Toolbar myToolbar = (Toolbar) rootView.findViewById(R.id.my_toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.header, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
Actually to include a action bar in fragment.Remove the on menu function and put relative layout inside your toolbar in layout.Inside this relative layout adda imageview with he appropriate position that you want.You are getting a blank space because of the empty toolbar area.Adding view inside it will show the image you want to show.

Implementing sliding tab within fragment

I have a navigation drawer and against each item within the drawer there is one fragment page. I want to implement tabbed swipe within one fragment. How do I do that.
Here's my code after clicking to one navigation drawer fragment page. I want to implement the tabbed view within this page. What's the way?
//Code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class SalesFragment extends Fragment {
private Toolbar mToolbar;
public SalesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sales, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.toolbar_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#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.add_user) {
return true;
}
if (id == R.id.barcode_scanner) {
return true;
}
if (id == R.id.search_overflow) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
//and here is the layout xml page
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.soumya.possystem.SalesFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Sales page"
android:textSize="40dp"/>
</FrameLayout>
You can created tabbed fragment page viewer by using Android Studio Activity Gallery. Just follow the below steps and create in half minute.
-> File -> New -> Activity -> Choose the type Tabbed Activity
-> Choose Navigation Style Action Bar Tabs (With ViewPager)
Enjoy Coding !

Not able to align fragment to parent activity without removing navigation bar

I am in the process of writing an android version of a iOS app I have helped create.
I am using a template navigation menu which puts a bar at the top and a menu at the side when dragged out or a button is pressed. This works fine, however the fragment comes with margins which leaves blank spaces between the bar and the layout.
I have tried removing the margins, but they then prevent the menu at the top from showing.
I am not sure which code snipped to include, so I have included the home.xml (fragment) activity_main.xml and the java files associated.
home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_marginTop="70dp"
android:layout_marginLeft="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/tvNo"
android:layout_gravity="left" />
</LinearLayout>
activity_main.xml
<!-- The main content view -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The ActionBar -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</include>
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/lvDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:paddingTop="24dp"
android:divider="#android:color/darker_gray"
android:dividerHeight="0dp"
android:background="#android:color/background_light" />
</uk.co.mrgyro.cropcirclelocatorandroid.FragmentNavigationDrawer>
Home.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import uk.co.mrgyro.cropcirclelocatorandroid.R;
public class Home extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.home, container, false);
return rootView;
}
}
MainActivity.java
package uk.co.mrgyro.cropcirclelocatorandroid;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private FragmentNavigationDrawer dlDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a ToolBar to replace the ActionBar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
dlDrawer = (FragmentNavigationDrawer) findViewById(R.id.drawer_layout);
// Setup drawer view
dlDrawer.setupDrawerConfiguration((ListView) findViewById(R.id.lvDrawer), toolbar,
R.layout.drawer_nav_item, R.id.flContent);
// Add nav items
dlDrawer.addNavItem("First", R.drawable.ic_one, "First Fragment", Home.class);
dlDrawer.addNavItem("Second", R.drawable.ic_two, "Second Fragment", SecondFragment.class);
dlDrawer.addNavItem("Third", R.drawable.ic_three, "Third Fragment", ThirdFragment.class);
// Select default
if (savedInstanceState == null) {
dlDrawer.selectDrawerItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
if (dlDrawer.isDrawerOpen()) {
// Uncomment to hide menu items
// menu.findItem(R.id.mi_test).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Uncomment to inflate menu items to Action Bar
// inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (dlDrawer.getDrawerToggle().onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
dlDrawer.getDrawerToggle().syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
This is how it looks with the margins added
This is how it looks with both margins in home.xml set to 0
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
The appearance I would like is like the first image, except with no blank space.
Thank you in advance
I dont understand very well your activities design and your layouts. If you need a navigation drawer and an action bar, I would just create one activity which extends ActionBarActivityand the navigation drawer written in the main xml. then in the content side of the navigation drawer place your activity content. In the code retrieve the action bar and the drawer and customize them as you want. You wont probably have those issues with margins etc and would be much more clean.
Remove
android:layout_marginTop="70dp"
android:layout_marginLeft="20dp"
from your Home layout, and
android:fitsSystemWindows="true"
from your activity layout.

Eclipse, Add libraries in Project. I'm stuck

I'm stuck when Add libraries in my project in Eclipse. I am following this link official android development website http://developer.android.com/tools/support-library/setup.html#libs-with-res and I do exactly what it says but I get errors for some reason.Here how it happends:
1.I download support libraries from SDK Manager.
2.I import them with existing Android Code into workspace and I press on the both .jar files Build Path>Add to Build Path.
3. Then on that project (made in step 2) I configure Build Path and I check both .jar files and uncheck the Android Dependencies and I click finish. Everything is okay for now.
But here comes the main problem=>
4. I press on my main project (myfirstapp) properties and click Add and select the libraries after that I press Apply and lots of errors raise up like R cannot be resolved to do variable and my R.id from /gen folder suddenly dissapear
I add now some screen shoots to make it better for you.
Sorry I have no reputations for posting images. Please copy links below
first image
second image
third image
fourth image
All my Codes: MainActivity.xml
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#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();
}
}
public void sendMessage(View view) {
Intent intent = new Intent(this, Displaymessageactivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#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;
}
}
}
fragment_main.xml
<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="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myfirstapp</string>
<string name="action_settings">Settings</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="title_activity_displaymessageactivity">Displaymessageactivity</string>
<string name="hello_world">Hello world!</string>
</resources>
Displaymessageactivity.xml
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Displaymessageactivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.displaymessageactivity, 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_displaymessageactivity, container, false);
return rootView;
}
}
}
fragment_displaymessageactivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.Displaymessageactivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Things I have tried so far:
1. Reinstall Eclipse and Java
2. Redownload libraries from SDK Manager
3. Clean the Project.
4. Make all my xml files starting with lowercase (but the MainActivity.xml and Displaymessageactivity.xml must start with uppercase)
I tried my best and I am stuck here forever. I am very frustated from Google :/
Every help is very appreciated and welcome!
Add the library to your application project:
In the Project Explorer, right-click your project and select Properties.
In the category panel on the left side of the dialog, select Android.
In the Library pane, click the Add button.
In step 3, notice that in the Library pane, you should see that the appcompat_v7 already be added (it's added automatically when you create your project follow MyFirstApp instruction, because you have already chosen minSdkVersion=8, not 11) (your second image).
So remove all the added libraries in the Library pane before adding your library (so in your third image it only has android-support-v7-appcompat in Library Pane), then the R.java will not disappear.

Android: fill actionbar list dynamically

I'm using SherlockActionbar and I wanted to fill dynamically the ListNavigation spinner in the actionbar. The problem is that my list navigation doesn't display anything. However the app is running on the emulator without any errors.
Here is the activity code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
public class TestView extends SherlockFragmentActivity {
private ArrayAdapter<String> listnav;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.test_view_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar ab = getSupportActionBar();
ab.setDisplayShowTitleEnabled(false);
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
Context context = ab.getThemedContext();
setContentView(R.layout.test_view);
List<String> items = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.testarray)));
listnav = new ArrayAdapter<String>(context, R.layout.sherlock_spinner_item, items);
listnav.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
}
}
Here is the code for the array resource:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testarray">
<item >2011</item>
<item >2012</item>
</string-array>
</resources>
I solved this problem. The spinner in the actionbar can be accessed with the setListNavigationCallbacks.
For more Information about this method click here
I solved this problem. The spinner in the actionbar can be accessed with the setListNavigationCallbacks. For more Information about this method click here

Categories

Resources