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).
Related
I have a navigation activity, where i also have a recycle view and a toolbar, to use the toolbar and the recycle view on this view, I created a separate XML layout like this:
<android.support.design.widget.CoordinatorLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.afcosta.inesctec.pt.android.PlantFeed">
<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="#color/emerald"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.v7.widget.RecyclerView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:backgroundTint="#f1c40f"
android:src="#android:drawable/ic_menu_camera" />
<include layout="#layout/content_plant_feed" />
</android.support.design.widget.CoordinatorLayout>
After this I included this layout on my main activity like this:
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_plant_feed"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_plant_feed"
app:menu="#menu/activity_plant_feed_drawer"
android:background="#color/white"/>
</android.support.v4.widget.DrawerLayout>
I am populating the recycler view with data of my database using also cardview, the thing is that with this approach (using include) my recycle view doesn't scroll, i have a lot of items but it always show just 4 of them.
my adapter:
public class PlantFeedAdapter extends RecyclerView.Adapter<PlantFeedAdapter.ViewHolder> {
private OnItemClickListener listener;
public interface OnItemClickListener {
void onRowClick(int position, String name, int id, View view);
void onTitleClicked(int position, int id, View clickedview);
void onImageClicked(int position,int id, View clickedview);
void onReportClicked(int position, int id,String name, View clickedview);
void onUserIconClicked(int position, int id, View clickedview);
void onUsernameClicked(int position, int id, View clickedview);
void onAvaliationClicked(int position, int id,String name, View clickedview);
}
private ArrayList<PlantPhotoUser> photos;
private Context context;
public PlantFeedAdapter(Context context, ArrayList<PlantPhotoUser> photos, OnItemClickListener listener) {
this.photos = photos;
this.context = context;
this.listener = listener;
}
#Override
public PlantFeedAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.plant_feed_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final PlantFeedAdapter.ViewHolder viewHolder, final int i) {
viewHolder.name.setText(photos.get(i).getSpecie());
viewHolder.username.setText(photos.get(i).getUsernName());
viewHolder.data.setText(photos.get(i).getDate().split("T")[0]);
Log.d("data123",(photos.get(i).getDate().toString()));
final String urlFoto = "http://10.0.2.2:3000/" + photos.get(i).getPath();
viewHolder.userIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onUserIconClicked(viewHolder.getAdapterPosition(), photos.get(i).getUserId(), view);
}
}
});
viewHolder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onUsernameClicked(viewHolder.getAdapterPosition(),photos.get(i).getUserId(), view);
}
}
});
viewHolder.plantImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onImageClicked(viewHolder.getAdapterPosition(), photos.get(i).getIdPlant(), view);
}
}
});
viewHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onTitleClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),v);
}
}
});
viewHolder.reportImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onReportClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
}
}
});
viewHolder.avaliationFoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onAvaliationClicked(viewHolder.getAdapterPosition(),photos.get(i).getIdPlant(),photos.get(i).getSpecie(),v);
}
}
});
Picasso.with(context)
.load(urlFoto)
.resize(300, 300)
.into(viewHolder.plantImg);
}
#Override
public int getItemCount() {
return photos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name;
private ImageView userIcon;
private TextView avaliationFoto;
private ImageView plantImg;
private ImageView foto;
private TextView username;
private ImageView reportImage;
private TextView data;
public ViewHolder(View view) {
super(view);
data = (TextView)view.findViewById(R.id.data);
name = (TextView) view.findViewById(R.id.plantName);
avaliationFoto = (TextView)view.findViewById(R.id.Avaliation);
userIcon = (ImageView)view.findViewById(R.id.userIcon);
plantImg = (ImageView)view.findViewById(R.id.plantPhoto);;
username = (TextView)view.findViewById(R.id.username);
reportImage = (ImageView)view.findViewById(R.id.cameraForbiden);
}
}
}
activity code:
public class PlantFeed extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {
//initialize fields
String token;
ArrayList<PlantPhotoUser> photos = new ArrayList<>();
VolleyService mVolleyService;
IResult mResultCallback = null;
final String GETREQUEST = "GETCALL";
final String URL = "http://10.0.2.2:3000/fotos";
String date;
String lat;
String lon;
String alt;
PlantFeedAdapter plantFeedAdapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant_feed);
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) {
Intent i = new Intent(PlantFeed.this,CameraCapture.class);
startActivity(i);
}
});
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);
recyclerView = (RecyclerView)findViewById(R.id.recycleView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager((new LinearLayoutManager(this)));
plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
recyclerView.setAdapter(plantFeedAdapter);
token = checkForToken();
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL,token);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d("HELLL","hi1");
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
PlantPhotoUser plantPhotoUser;
Log.d("HELLLL","hi");
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Log.d("objeto",object.toString());
int userId = object.getInt("userId");
Log.d("objeto",String.valueOf(userId));
String username = object.getJSONObject("user").getString("username");
Log.d("objeto",String.valueOf(username));
int plantId = object.getInt("plantId");
Log.d("objeto",String.valueOf(plantId));
String specie = object.getJSONObject("plant").getString("specie");
Log.d("objeto",String.valueOf(specie));
String path = object.getString("image");
Log.d("objeto",String.valueOf(path));
int fotoId = object.getInt("id");
if(object.getString("date") != null){
date = object.getString("date");
}
if(object.getString("lat") != null){
lat = object.getString("lat");
}
if(object.getString("lon") != null){
lon = object.getString("lon");
}
if(object.getString("altitude") != null){
alt = object.getString("altitude");
}
plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
photos.add(plantPhotoUser);
} catch (JSONException e) {
e.printStackTrace();
}
}
plantFeedAdapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d("FAIL",error.toString());
}
};
}
public String checkForToken() {
SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
String tokenKey = getResources().getString(R.string.token);
String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
return token;
}
#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) {
Intent i = new Intent(PlantFeed.this,UserProfile.class);
startActivity(i);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.plant_feed, 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Intent i = new Intent(PlantFeed.this,CameraCapture.class);
startActivity(i);
} else if (id == R.id.nav_gallery) {
Intent i = new Intent(PlantFeed.this,PlantFeed.class);
startActivity(i);
} else if (id == R.id.nav_slideshow) {
Intent i = new Intent(PlantFeed.this,FamilyLibrary.class);
startActivity(i);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onRowClick(int position, String name, int id, View view) {
}
#Override
public void onTitleClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,PhotosForPlant.class);
i.putExtra("plantId",String.valueOf(id));
startActivity(i);
}
#Override
public void onImageClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,PhotosForPlant.class);
i.putExtra("plantId",String.valueOf(id));
startActivity(i);
}
#Override
public void onReportClicked(int position, int id, String name, View clickedview) {
Log.d("HELLLO","HELLOO");
showDialogReport(id,name);
}
#Override
public void onUserIconClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,UserProfile.class);
i.putExtra("userId",id);
startActivity(i);
}
#Override
public void onUsernameClicked(int position, int id, View clickedview) {
Intent i = new Intent(this,UserProfile.class);
i.putExtra("userId",id);
startActivity(i);
}
#Override
public void onAvaliationClicked(int position, int id, String name, View clickedview) {
}
Any tip?
I am trying to implement recycler view instead of an expandable list view,so that when I click a navigation drawer menu item,t should expand.Her is my code,I don't how to implement.
activity_main.xml:
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer"
app:itemTextAppearance="#style/NavDrawerTextStyle"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#fff">
</android.support.v7.widget.RecyclerView>
and this is Adapter
public class ExpandableListCustomAdapter extendsRecyclerView.Adapter{
private List<SubMenuItems> subMenuItemses_list=new ArrayList<>();
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView sample_text;
public MyViewHolder(View itemView) {
super(itemView);
sample_text=(TextView)itemView.findViewById(R.id.sample_text);
}
}
public ExpandableListCustomAdapter(List<SubMenuItems> subMenuItemses_list){
this.subMenuItemses_list=subMenuItemses_list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.expandable_list_custom_adapter,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SubMenuItems subMenuItems=subMenuItemses_list.get(position);
holder.sample_text.setText(subMenuItems.getItem1());
}
#Override
public int getItemCount() {
return subMenuItemses_list.size();
}
}
MainActivity.java
ExpandableListCustomAdapter expandableListCustomAdapter=new ExpandableListCustomAdapter(subMenuItemses2);
layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
prepareSubMenu();
//here we configured text,images and added to a list
recyclerView.setAdapter(expandableListCustomAdapter);
private void prepareSubMenu(){
SubMenuItems subMenuItems4=new SubMenuItems("Main");
subMenuItemses2.add(subMenuItems4);
subMenuItems4=new SubMenuItems("Starters");
subMenuItemses2.add(subMenuItems4);
subMenuItems4=new SubMenuItems("Dessert");
subMenuItemses2.add(subMenuItems4);
expandableListCustomAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home_id) {
/*Toast.makeText(MainActivity.this, "Wait on....", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MediaStore.ACTION_IMAGE_CAPTURE));*/
// Handle the camera action
} else if (id == R.id.menu_id) {
} else if (id == R.id.my_order_id) {
} else if (id == R.id.about_id) {
} else if (id == R.id.contact_id) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer != null) {
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
}
Result is showing,that's not an issue.I need to implement this when someone click an item in Nav Drawer,and shows an expand list.Here I am using RecyclerView.Is it possible or I have to use ExpandableList ?
If you want to add Expandable list in your drawer try to follow expandable-navigation-drawer
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private Map<String, List<String>> mExpandableListData;
private TextView mSelectedItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mSelectedItemView = (TextView) findViewById(R.id.selected_item);
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
mSelectedItemView.setText(R.string.selected_item);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString() + " -> " + selectedItem);
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.film_genres);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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) {
// 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) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am using appcompat v7 and support design 23.1.1.
I want to add back button in the hamburger button animation, when back pressed application will go back to started page.
Now in my application I have hamburger button. When it is pressed in main window (marked with orange rectangle) material navigation opens, selected Home (marked as red rectangle) when the application navigates to selected window there are hamburger (yellow rectangle) button again, and I would like to change it.
My MainActivity.java:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new PagerAdapter(this));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStack();
}
});
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
}
#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:
return true;
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
mToolbar.setTitle(title);
}
}
}
FragmentDrawer.java:
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
NavDrawerItem.java:
public class NavDrawerItem {
private boolean showNotify;
private String title;
public NavDrawerItem() {
}
public NavDrawerItem(boolean showNotify, String title) {
this.showNotify = showNotify;
this.title = title;
}
public boolean isShowNotify() {
return showNotify;
}
public void setShowNotify(boolean showNotify) {
this.showNotify = showNotify;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
DrawerActivity.java :
public class DrawerActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
Try this way in your xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_gravity="start"
android:background="#android:color/transparent"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/toolBarStyle"
app:titleTextAppearance="#style/Toolbar.TitleText" />
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
android:background="#android:color/transparent" />
<fragment
android:id="#+id/navigation_drawer"
class="com.buzzintown.consumer.drawer.NavigationDrawerFragment"
android:layout_width="310dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/drawer_layout" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
If the activity figured in your third picture is a new one, you can just add the follow code in the new activity`s onCreate() method. it may help...
final ActionBar toolbar = getSupportActionBar();
if (toolbar != null) {
toolbar.setDisplayHomeAsUpEnabled(true);
}
If it`s in one same activity, and just different fragments through viewpager, use the Toolbar.setNavigationIcon() to change your up icon.
I have 3 tabs in my dashboard namely,
Invitation
Event
Groupchat
I am added all those tabs programmatically,In my layout code id:tabContent using for add all my tabs. My Userdashboard.xml code is below,
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-4dp"
android:layout_weight="0" />
</LinearLayout>
In below code all tabs are grouped as "tabHost". Now i am need to set unique id for all the three tabs, but i dont know how to set unique id for that help me please thanks in advance.
public class UserDashBoardActivity extends ActionBarActivity {
/** Called when the activity is first created. */
private static final String TAB_1_TAG = "Invitation";
private static final String TAB_2_TAG = "Event";
private static final String TAB_3_TAG = "GroupChat";
private FragmentTabHost tabHost;
private Context context;
private SharedPreferences sharedpreferences;
private Gson gson = new Gson();
private Menu menu;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.menu=menu;
getMenuInflater().inflate(R.menu.menu_user_dash_board, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
// Get TabHost Reference
tabHost= (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
**Invitation,Event,Groupchat tabs** are added here
tabHost.addTab(tabHost.newTabSpec(TAB_1_TAG).setIndicator("Invitation"), InvitationFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_2_TAG).setIndicator("Event"), OccasionFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_3_TAG).setIndicator("GroupChat"), GroupChatFragment.class, null);
//invitation tab highlighted by default
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.Orange));
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.scandal));
tabHost.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.scandal));
//onTabChangedListener added for move one tab to others
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
setTabColor(tabHost);
}
});
}
if(tabHost.getCurrentTab()==0)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange));//1st tab selected
else if(tabHost.getCurrentTab()==1)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //2nd tab selected
else if(tabHost.getCurrentTab()==2)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //3rd tab selected
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.account_settings) {
Intent userSettingIntent = new Intent(getApplicationContext(),ActivityUserSettings.class);
userSettingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(userSettingIntent);
return true;
}
if (id == R.id.profile) {
Intent profileIntent = new Intent(getApplicationContext(),ImageUploadActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profileIntent);
return true;
}
if(id == R.id.create_occasion){
Intent occasionAct = new Intent(getApplicationContext(), OccasionActivity.class);
// Clears History of Activity
occasionAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(occasionAct);
}
return super.onOptionsItemSelected(item);
}
}
The call to tabHost.newTabSpec() takes a String as tag. In your case these are TAB_1_TAG, TAB_2_TAG, TAB_3_TAG, so these are your unique IDs for each tab respectively.
You can identify the selected tab in onTabChanged(String arg0) here arg0 is the name of the selected tag.
Furthermore you can use tabHost.getCurrentTabTag() to identify tabs by tag instead of tabHost.getCurrentTab() which is by tab position.
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