Up caret shows navigation drawer - android

Nothing much more to say. I'm using a single activity and I go into a Fragment which calls setDisplayHomeAsUpEnabled(Boolean.TRUE) and setHasOptionsMenu(Boolean.TRUE). The menu has two items and the interactions with them are right. I have set breakpoints on all onOptionsItemSelected of the app (which includes the Activity, the Fragment, and the drawer toggle) but when I debug, the menu opens and no breakpoint is triggered.
The Activity and Fragment code in case they help:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/navigation_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:animateLayoutChanges="true">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/content_fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="#+id/navigation_drawer_fragment"
android:name="org.jorge.lolin1.ui.fragment.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
layout="#layout/fragment_navigation_drawer" />
The Fragment code:
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
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.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ScrollView;
import android.widget.TextView;
import com.melnykov.fab.FloatingActionButton;
import com.squareup.picasso.Picasso;
import org.jorge.lolin1.LoLin1Application;
import org.jorge.lolin1.R;
import org.jorge.lolin1.datamodel.FeedArticle;
import org.jorge.lolin1.ui.activity.MainActivity;
import org.jorge.lolin1.ui.util.StickyParallaxNotifyingScrollView;
import org.jorge.lolin1.util.PicassoUtils;
public class ArticleReaderFragment extends Fragment {
private Context mContext;
private int mDefaultImageId;
private String TAG;
private FeedArticle mArticle;
public static final String ARTICLE_KEY = "ARTICLE";
private MainActivity mActivity;
private Drawable mActionBarBackgroundDrawable;
private final Drawable.Callback mDrawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
final ActionBar actionBar = mActivity.getSupportActionBar();
if (actionBar != null)
actionBar.setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
}
};
private ActionBar mActionBar;
private float mOriginalElevation;
private FloatingActionButton mMarkAsReadFab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = LoLin1Application.getInstance().getContext();
Bundle args = getArguments();
if (args == null)
throw new IllegalStateException("ArticleReader created without arguments");
mArticle = args.getParcelable(ARTICLE_KEY);
TAG = mArticle.getUrl();
mActivity = (MainActivity) activity;
mDefaultImageId = getArguments().getInt(FeedListFragment.ERROR_RES_ID_KEY);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.actionbar_article_reader, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.homeAsUp:
mActivity.onBackPressed();
return Boolean.TRUE;
case R.id.action_browse_to:
mArticle.requestBrowseToAction(mContext);
return Boolean.TRUE;
case R.id.action_share:
mArticle.requestShareAction(mContext);
return Boolean.TRUE;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
mActionBarBackgroundDrawable.setCallback(mDrawableCallback);
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(Boolean.TRUE);
final View ret = inflater.inflate(R.layout.fragment_article_reader, container, Boolean.FALSE);
View mHeaderView = ret.findViewById(R.id.image);
PicassoUtils.loadInto(mContext, mArticle.getImageUrl(), mDefaultImageId, (android.widget.ImageView) mHeaderView, TAG);
final String title = mArticle.getTitle();
mHeaderView.setContentDescription(title);
((TextView) ret.findViewById(R.id.title)).setText(title);
((TextView) ret.findViewById(android.R.id.text1)).setText(mArticle.getPreviewText());
mActionBar = mActivity.getSupportActionBar();
mActionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE);
mActionBarBackgroundDrawable = new ColorDrawable(mContext.getResources().getColor(R.color.toolbar_background));
mActionBar.setBackgroundDrawable(mActionBarBackgroundDrawable);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mOriginalElevation = mActionBar.getElevation();
mActionBar.setElevation(0); //So that the shadow of the ActionBar doesn't show over the article title
}
mActionBar.setTitle(mActivity.getString(R.string.section_title_article_reader));
StickyParallaxNotifyingScrollView scrollView = (StickyParallaxNotifyingScrollView) ret.findViewById(R.id.scroll_view);
scrollView.setOnScrollChangedListener(mOnScrollChangedListener);
scrollView.smoothScrollTo(0, 0);
if (!mArticle.isRead()) {
mMarkAsReadFab = (FloatingActionButton) ret.findViewById(R.id.fab_button_mark_as_read);
mMarkAsReadFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mArticle.markAsRead();
mMarkAsReadFab.hide();
}
});
mMarkAsReadFab.show();
}
return ret;
}
private StickyParallaxNotifyingScrollView.OnScrollChangedListener mOnScrollChangedListener = new StickyParallaxNotifyingScrollView.OnScrollChangedListener() {
public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
if (mMarkAsReadFab != null)
if (!who.canScrollVertically(1)) {
mMarkAsReadFab.show();
} else if (t < oldt) {
mMarkAsReadFab.show();
} else if (t > oldt) {
mMarkAsReadFab.hide();
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
Picasso.with(mContext).cancelTag(TAG);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mActionBar.setElevation(mOriginalElevation);
}
}
#Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (enter) {
return AnimationUtils.loadAnimation(mContext, R.anim.move_in_from_bottom);
} else {
return AnimationUtils.loadAnimation(mContext, R.anim.move_out_to_bottom);
}
}
}

I have opted for making an activity only for that fragment which doesn't include the nav drawer. But obviously this doesn't answer the question, it just gets a relatively similar behavior.

Related

NavigationDrawer in certain fragment

Here is the problem, I want my navigation drawer (the hamburger icon), only appears in certain fragment. In my case, I have three fragment, using tab layout and view pager to change between fragment. I have implement an interface which I have created. But when I set to true, the hamburger icon appear in all fragment. I don't know where my problem is in my code.
mainactivity code :
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import emptrack.toro.developer.com.emptrack.FastScroll.AlphabetItem;
import emptrack.toro.developer.com.emptrack.FastScroll.DataHelper;
import emptrack.toro.developer.com.emptrack.FastScroll.VendorAdapter;
import in.myinnos.alphabetsindexfastscrollrecycler.IndexFastScrollRecyclerView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DrawerLocker{
private View view_menu, view_click, view_list;
private ImageView btn_arrow_back;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;
private Bundle intentFragment;
private String frag;
private ArrayList<ListPegawai> dataBaru;
private Bundle dapatData;
String PREFERENCES_FILE_NAME = "preference_diri";
SharedPreferences dataDiri, retrieveData;
//Untuk filtering
private List<String> mDataArray;
//Side bar
private DrawerLayout drawer;
ActionBarDrawerToggle toggle;
Toolbar toolbar;
private List<AlphabetItem> mAlphabetItems;
private IndexFastScrollRecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Filtering
mRecyclerView = findViewById(R.id.fast_scroller_recycler);
mDataArray = new ArrayList<String>();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ganti ActionBar font
SpannableString s = new SpannableString("EmpTrack");
s.setSpan(new TypefaceSpan(this, "raleway_semibold.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(0);
actionBar.setTitle(s);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
dataDiri = getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = dataDiri.edit();
adapter.addFragment(new FragmentNews(), "News");
adapter.addFragment(new FragmentTracking(), "Tracking");
adapter.addFragment(new FragmentSettings(), "Settings");
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
//Init layout
view_menu = (View) findViewById(R.id.menu_layout);
view_list = (View) findViewById(R.id.list_vendor2);
view_click = (View) findViewById(R.id.click_vendor);
btn_arrow_back = (ImageView) findViewById(R.id.arrow_back);
//Untuk sidebar
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
//Init filtering
initialiseData();
initialiseUI();
tabLayout.getTabAt(0).setIcon(R.drawable.ic_news);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_tracking);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_settings);
actionBar.setElevation(0);
intentFragment = getIntent().getExtras();
if (intentFragment != null) {
frag = intentFragment.getString("LoadFragment");
switch (frag) {
case "tracking":
viewPager.setCurrentItem(1, true);
break;
case "settings":
viewPager.setCurrentItem(2, true);
break;
}
}
//Fungsi click untuk sidebar
view_click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view_menu.setVisibility(View.GONE);
view_list.setVisibility(View.VISIBLE);
}
});
btn_arrow_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view_list.setVisibility(View.GONE);
view_menu.setVisibility(View.VISIBLE);
}
});
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
builder1.setTitle("Exit application");
builder1.setMessage("Are you sure you want to exit?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(toggle.onOptionsItemSelected(item)){
return true;
}
else {
return super.onOptionsItemSelected(item);
}
}
protected void initialiseData() {
//Recycler view data
mDataArray = DataHelper.getAlphabetData();
//Alphabet fast scroller data
mAlphabetItems = new ArrayList<>();
List<String> strAlphabets = new ArrayList<>();
for (int i = 0; i < mDataArray.size(); i++) {
String name = mDataArray.get(i);
if (name == null || name.trim().isEmpty())
continue;
String word = name.substring(0, 1);
if (!strAlphabets.contains(word)) {
strAlphabets.add(word);
mAlphabetItems.add(new AlphabetItem(i, word, false));
}
}
}
protected void initialiseUI() {
Typeface typeface = Typeface.createFromAsset(this.getAssets(), "font/raleway_medium.ttf");
mRecyclerView.setTypeface(typeface);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(new VendorAdapter(mDataArray));
mRecyclerView.setIndexTextSize(14);
mRecyclerView.setIndexBarColor("#ffffff");
mRecyclerView.setIndexBarCornerRadius(0);
mRecyclerView.setIndexBarTransparentValue((float) 0.4);
mRecyclerView.setIndexbarMargin(0);
mRecyclerView.setIndexbarWidth(40);
mRecyclerView.setPreviewPadding(0);
mRecyclerView.setIndexBarTextColor("#000000");
// mRecyclerView.setPreviewTextSize(60);
// mRecyclerView.setPreviewColor("#33334c");
// mRecyclerView.setPreviewTextColor("#FFFFFF");
// mRecyclerView.setPreviewTransparentValue(0.6f);
mRecyclerView.setIndexBarVisibility(true);
mRecyclerView.setIndexbarHighLateTextColor("#000000");
mRecyclerView.setIndexBarHighLateTextVisibility(true);
}
#Override
public void setDrawerLocked(boolean shouldLock) {
if(shouldLock) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
toggle.setDrawerIndicatorEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
toggle.setDrawerIndicatorEnabled(false);
}
}
}
And here is the fragment code :
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
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.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.daimajia.swipe.util.Attributes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
public class FragmentTracking extends Fragment implements Serializable, SearchView.OnQueryTextListener, SwipeRefreshLayout.OnRefreshListener, PegawaiItemClickListener {
private final String url = "https://opensource.petra.ac.id/~m26415177/getPegawai.php";
private JsonArrayRequest request;
private RequestQueue queue;
View v;
SwipeRefreshLayout swipeLayout;
private RecyclerView mRecyclerView;
private List<ListPegawai> pegawaiList;
FloatingActionButton buttonAdd;
SwipeRecyclerViewAdapter mAdapter;
SearchView search_view_bawah;
public static final String PREFERENCES_FILE_NAME = "preference_diri";
SharedPreferences dataDiri, retrieveData;
#SuppressLint("ResourceAsColor")
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.tracking_fragment,container,false);
setHasOptionsMenu(true);
retrieveData = this.getActivity().getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE);
dataDiri = this.getActivity().getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = dataDiri.edit();
//((MainActivity) getActivity()).setDrawerLocked(true);
swipeLayout = (SwipeRefreshLayout) v.findViewById(R.id.container2);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(android.R.color.holo_green_dark,
android.R.color.holo_red_dark,
android.R.color.holo_blue_dark,
android.R.color.holo_orange_dark);
mRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
mAdapter = new SwipeRecyclerViewAdapter(getContext(), this);
mAdapter.setMode(Attributes.Mode.Single);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
Log.e("RecyclerView", "onScrollStateChanged");
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
pegawaiList = new ArrayList<ListPegawai>();
buttonAdd = (FloatingActionButton)v.findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intentAdd = new Intent(getContext(), InsertEmployeeActivity.class);
startActivity(intentAdd);
getActivity().overridePendingTransition(R.anim.fadein,R.anim.fadeout);
getActivity().finish();
}
});
jsonRequest();
if (!isViewShown) {
animasiOn();
}
else {
}
return v;
}
private void animasiOn() {
mRecyclerView.setVisibility(View.INVISIBLE);
AnimationSet set = new AnimationSet(true);
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(500);
set.addAnimation(animation);
animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
);
animation.setDuration(100);
set.addAnimation(animation);
LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
mRecyclerView.setLayoutAnimation(controller);
set.start();
mRecyclerView.setVisibility(View.VISIBLE);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
pegawaiList = new ArrayList<ListPegawai>();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.search_icon,menu);
MenuItem item = menu.findItem(R.id.search_all);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
// String userInput = s.toLowerCase();
// List<ListPegawai> newList = new ArrayList<ListPegawai>();
//
// for(ListPegawai name:mDataSet){
// if(name.getNama().toLowerCase().contains(userInput)){
// newList.add(name);
// }
// }
//
// mAdapter.updateList(newList);
return true;
}
private boolean isViewShown = false;
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
if (isVisibleToUser) {
animasiOn();
}
else {
mRecyclerView.setVisibility(View.INVISIBLE);
}
} else {
isViewShown = false;
}
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
animasiOn();
mAdapter.setPegawaiList(pegawaiList);
swipeLayout.setRefreshing(false);
pegawaiList = new ArrayList<ListPegawai>();
jsonRequest();
}
}, 750);
}
private void jsonRequest() {
request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
Log.d("LENGTH",String.valueOf(response.length()));
jsonObject = response.getJSONObject(i);
ListPegawai pegawai = new ListPegawai();
pegawai.setNama(jsonObject.getString("nama"));
pegawai.setNik(jsonObject.getString("nik"));
pegawai.setAlamat(jsonObject.getString("alamat"));
pegawai.setTanggal(jsonObject.getString("tanggal_kejadian"));
pegawai.setJenisKelamin(jsonObject.getString("jenis_kelamin"));
pegawai.setKeluhanPegawai(jsonObject.getString("keluhan"));
pegawaiList.add(pegawai);
} catch (JSONException e) {
e.printStackTrace();
}
}
setuprecyclerview(pegawaiList);
mAdapter.setPegawaiList(pegawaiList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
queue = Volley.newRequestQueue(getContext());
queue.add(request);
}
private void setuprecyclerview(List<ListPegawai> pegawaiList) {
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), LinearLayoutManager.VERTICAL));
mRecyclerView.setAdapter(mAdapter);
Log.d("KUDA","KUDANS");
}
#Override
public void onPegawaiItemClick(int pos, ListPegawai pegawaiList) {
}
#Override
public void onDestroyView() {
super.onDestroyView();
((MainActivity) getActivity()).setDrawerLocked(false);
}
}
When I set this code ((MainActivity) getActivity()).setDrawerLocked(true); the hamburger icon appear in all fragment. But, when I comment it, the icon not appear in all fragment
Here is the XML code, in case my mistake there :
<?xml version="1.0" encoding="utf-8"?>
<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:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout 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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="emptrack.toro.developer.com.emptrack.MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
app:tabGravity="fill"
app:tabIconTint="#FFFFFF"
app:tabIndicatorColor="#FFFFFF"
app:tabMode="fixed"
app:tabTextAppearance="#style/tab_text"
app:tabTextColor="#FFFFFF"></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/tabLayout" />
</RelativeLayout>
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical"
android:paddingTop="0dp">
<include
android:id="#+id/menu_layout"
layout="#layout/list_menu" />
<include
android:id="#+id/list_vendor2"
layout="#layout/list_vendor"
android:visibility="gone" />
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Just ask for more detailed, thanks
Just add tab Layout change listener and hide and show icon according to the requirement.
Navigation is in hidden mode, change it to visible.. it will work

whenever i run the app on emulator it says unfortunately the app has stopped working and the log reads the below lines

The MainActivity file
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
I am getting this error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}: java.lang.ClassCastException: minor_activities.Status cannot be cast to com.example.intel.dualboot.MainFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: minor_activities.Status cannot be cast to com.example.intel.dualboot.MainFragment
at com.example.intel.dualboot.MainFragment.newFragment(MainFragment.java:28)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
here is your error...
android.support.v4.widget.SwipeRefreshLayout cannot be cast to com.example.intel.dualboot.InSwipeRefreshLayout
You have initialize SwipeToRefresh in XML as "android.support.v4.widget.SwipeRefreshLayout" But you are trying to create object of that view as "com.example.intel.dualboot.InSwipeRefreshLayout". So you got an error because of wrong casting of class. Change "android.support.v4.widget.SwipeRefreshLayout" to "com.example.intel.dualboot.InSwipeRefreshLayout" in xml to solve your problem.

whenever i run the app on emulator it says unfortunately the app has stopped working and the log reads as below

MainActivity.java
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.intel.dualboot, PID: 23319
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}:
java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2330)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:469)
at android.app.BackStackRecord.add(BackStackRecord.java:464)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
at android.app.ActivityThread.access$800(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5273) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372)
replace
com.exmaple.intel.dualboot.InSwipeRefreshLayout
with
android.support.v4.widget.SwipeRefreshLayout
in your xml file,
as the com.exmaple.intel.dualboot.InSwipeRefreshLayout class is not defined
com.exmaple.intel.dualboot.InSwipeRefreshLayout
Check this path if it is correct in your xml.It seems the path of "InSwipeRefreshLayout" is not corect
in your xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout">
<com.exmaple.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.exmaple.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
the com.exmaple.intel.dualboot.InSwipeRefreshLayout has that spelling of "exmaple", it should be example.
The posted layout working fine for me.Please check the package name properly com.example.intel.dualboot.InSwipeRefreshLayout whether exist or not and clean and build the project.

Changing Gridview Size from Preferences when Implementing Fragments

I had a gridview activity where I was populating the gridview with a custom object (a picture with some custom methods and an onclick listener). I could change the gridview size from the preferences menu. Everything worked beautifully.
I have since added some complexity to the code. Instead of using the normal Activity class, I am now using the FragmentActivity class, a fragmentPageAdapter, and a fragment to which my gridview is bound. This is because eventually I want the app to allow the user "swipe" from fragment to fragment.
Since using the fragment in this way, I am noticing a repeatable bug whenever I try to resize the gridview from the preferences menu: some of the objects get resized properly, other elements do not resize. Instead, they keep the same size that they had prior to changing the preference. Here is a screenshot:
This only happens when I try resizing from the preferences menu. Other calls to my resize method, such as on a configuration change, resize all of the gridview elements correctly.
I would appreciate any suggestions!
Here is my Code:
MAIN ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.GridView;
public class MainActivity extends FragmentActivity implements OnSharedPreferenceChangeListener{
private MyFragment m_myFragment = new MyFragment();
private ViewPager m_viewPager;
private static SharedPreferences m_prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_prefs.registerOnSharedPreferenceChangeListener(this);
setContentView(R.layout.activity_main);
m_viewPager = (ViewPager) findViewById(R.id.pager);
m_viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), m_myFragment));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i("Khalid","MainActivity: onSharedPreferenceChanged");
if (key.equals("key_prefs_enable_lscape")){
//do nothing for now
}else if (key.equals("key_prefs_picture_size")){
SetColumnWidth(m_myFragment.getM_gridView());
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("Khalid","FragAnimalSounds: onConfigurationChanged");
SetColumnWidth(m_myFragment.getM_gridView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("Khalid","MainActivity: onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbl_opt_menu_settings:
Intent i = new Intent("android.intent.action.PREFERENCES");
startActivity(i);
break;
case R.id.lbl_opt_menu_quit:
finish();
break;
default:
finish();
break;
}
return true;
}
public static void SetColumnWidth(GridView GV) {
Log.i("Khalid","MainActivity: SetColumnWidth");
int NumColumns, DesiredColumnWidth;
//Get the desired number of columns from the key prefs
NumColumns = Integer.parseInt(m_prefs.getString("key_prefs_picture_size","2"));
//Determine the desired column width
if (NumColumns == 1){
DesiredColumnWidth = 200;
}else if (NumColumns == 2){
DesiredColumnWidth = 100;
}else{
DesiredColumnWidth = 50;
}
//Set the desired column width
GV.setColumnWidth(DesiredColumnWidth);
}
}
class MyAdapter extends FragmentPagerAdapter{
Fragment m_frag_A = null;
public MyAdapter(FragmentManager fm, Fragment A) {
super(fm);
m_frag_A = A;
}
#Override
public Fragment getItem(int i) {
return m_frag_A; //only 1 item for now
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int i) {
return "Title Frag A"; //only 1 item for now
}
}
MY FRAGMENT (THERE IS ONLY ONE FOR NOW):
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class MyFragment extends Fragment {
private GridView m_gridView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i("Khalid","FragAnimalSounds: onCreateView");
View view = inflater.inflate(R.layout.activity_animal_sounds, container, false);
m_gridView = (GridView) view.findViewById(R.id.lbl_gridView);
m_gridView.setAdapter(new VivzAdapter(view.getContext()));
MainActivity.SetColumnWidth(m_gridView);
return view;
}
public GridView getM_gridView() {
return m_gridView;
}
}
MY GRIDVIEW ADAPTER:
package com.KhalidSorensen.animalsounds;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class VivzAdapter extends BaseAdapter {
private Context m_context;
private ArrayList<AnimalKind> m_list = new ArrayList<AnimalKind>();
VivzAdapter(Context ctx) {
m_context = ctx;
int[] animalphotos = { R.drawable.cat_1, R.drawable.cow_1,
R.drawable.dog_1, R.drawable.donkey_1, R.drawable.duck_1,
R.drawable.peacock_1, R.drawable.rooster_1, R.drawable.seal_1 };
for (int i = 0; i <= 7; i++) {
AnimalKind animalKind = new AnimalKind(m_context, animalphotos[i]);
m_list.add(animalKind);
}
}
#Override
public int getCount() {
return m_list.size();
}
#Override
public AnimalKind getItem(int position) {
return m_list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View v, ViewGroup vg) {
return m_list.get(i);
}
}
MY CUSTOM OBJECT CLASS. THESE OBJECTS ARE POPULATING THE GRIDVIEW:
package com.KhalidSorensen.animalsounds;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class AnimalKind extends ImageView implements OnClickListener{
private int m_imageId;
public AnimalKind(Context ctx, int imageId) {
super(ctx);
m_imageId = imageId;
super.setImageResource(imageId);
super.setAdjustViewBounds(true);
super.setScaleType(ImageView.ScaleType.FIT_XY);
super.setPadding(1, 1, 1, 1);
super.setBackgroundColor(Color.BLACK);
super.setOnClickListener(this);
}
//#Override
public void onClick(View v) {
//Do Something
}
#Override
public void setPressed(boolean pressed) {
//Do Something
}
public int getM_imageId() {
return m_imageId;
}
}
MY PREFERENCE ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Log.i("Khalid", "Preferences: onCreate");
}
}
MY XML FOR MY MAIN ACTIVITY:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lbl_title"
android:background="#33B5E5"
android:layout_gravity="top"
android:paddingTop="0dp"
android:paddingBottom="0dp"> "
</android.support.v4.view.PagerTitleStrip>
</android.support.v4.view.ViewPager>
AND FINALLY, MY XML FOR THE GRIDVIEW:
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lbl_gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="0px"
android:alwaysDrawnWithCache="false"
android:animateLayoutChanges="false"
android:background="#android:color/white"
android:columnWidth="130dp"
android:drawSelectorOnTop="true"
android:horizontalSpacing="#dimen/activity_horizontal_margin"
android:listSelector="#null"
android:numColumns="auto_fit"
android:padding="#dimen/activity_horizontal_margin"
android:scrollbarStyle="insideOverlay"
android:smoothScrollbar="true"
android:stretchMode="none"
android:verticalSpacing="#dimen/activity_vertical_margin" >
</GridView>
Use CENTER_INSIDE a scale type for your image view.
super.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
another thing that I would change is the way you handle the column width. I would remove the android:numColumns="auto_fit". On the other hand you know that the number of columns is the cealing of WidthViewGrid/desiderePicSize, where the most common case for WidthViewGrid is the screen's width. On then programmatically you can set number of columns of your GridView with setNumberOfColumns
I would say:
A. After calling setColumnWidth call the gridview.invalidate()
B. After returning from the change preference - call adapter's notifyDataSetChanged in order to make sure it re-creates the views in the adapter (i.e. getView will be called)

How to dynamically add user input into a listView within a fragment?

Im trying to add text into a listview within a fragment but i keep getting an error: cannot find symbol method setListAdapter(ArrayAdapter).
I'm using this tutorial as reference but it only shows how to do it within a activity : http://wptrafficanalyzer.in/blog/dynamically-add-items-to-listview-in-android/
Im trying to move this over to a fragment. Can anyone help please i would highly appreciate it? heres my code :
MainActivity:
import android.app.Activity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import com.example.fragments.DeleteDialogueFragment;
import com.example.PeopleFragment;
public class MainActivity extends Activity implements PeopleFragment.PeopleFragmentListener, DeleteDialogueFragment.DeleteDialogueListener {
private final String TAG = "MAINACTIVITY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PeopleFragment())
.commit();
}
}
#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);
}
//INTERFACE METHODS
public void deleteCharacter(){
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentById(R.id.container);
peopleFragment.deleteCharacter();
}
}
PeopleFragment :
import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.example.actionbardemo.R;
import java.util.ArrayList;
import java.util.Arrays;
public class PeopleFragment extends Fragment{
private final String TAG = "PEOPLEFRAGMENT";
private PeopleFragmentListener mListener;
private ArrayAdapter<String> mPeopleAdapter;
private ActionMode mActionMode;
private int mPersonSelected = -1;
/** Items entered by the user is stored in this ArrayList variable */
private ArrayList<String> pList = new ArrayList<String>();
public interface PeopleFragmentListener {
}
public static PeopleFragment newInstance() {
PeopleFragment fragment = new PeopleFragment();
return fragment;
}
public PeopleFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> people = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.people)));
mPeopleAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,people);
// Reference to the button of the layout main.xml
Button btn = (Button) getView().findViewById(R.id.btnAdd);
// Defining a click event listener for the button "Add"
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) getView().findViewById(R.id.txtItem);
pList.add(edit.getText().toString());
edit.setText("");
mPeopleAdapter.notifyDataSetChanged();
}
};
// Setting the event listener for the add button
btn.setOnClickListener(listener);
// Setting the adapter to the ListView
setListAdapter(mPeopleAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView peopleList = (ListView) rootView.findViewById(R.id.peopleList);
peopleList.setAdapter(mPeopleAdapter);
peopleList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(mActionMode != null){
return false;
}
mPersonSelected = position;
mActionMode = getActivity().startActionMode(mActionModeCallback);
return true;
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (PeopleFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement PeopleFragmentListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
//INTERFACE METHODS
public void deleteCharacter(){
mPeopleAdapter.remove(mPeopleAdapter.getItem(mPersonSelected));
mPeopleAdapter.notifyDataSetChanged();
}
public String getToDelete(){
return mPeopleAdapter.getItem(mPersonSelected);
}
//CONTEXTUAL ACTION BAR CALLBACK
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.peoplemenu, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.peopleDelete:
Log.i(TAG,mPeopleAdapter.getItem(mPersonSelected));
DialogFragment dialog = new DeleteDialogueFragment();
Bundle args = new Bundle();
args.putString("name",mPeopleAdapter.getItem(mPersonSelected));
dialog.setArguments(args);
dialog.show(getActivity().getFragmentManager(), "DeleteDiaglogueFragment");
mode.finish();
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
activity_main.xml (layout):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml (layout):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/hintTxtItem"/>
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/lblBtnAdd"
android:layout_toRightOf="#id/txtItem"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/peopleList"
android:layout_gravity="center_horizontal" />
</LinearLayout>
strings.xml(values):
<string name="app_name">ActionBarDemo</string>
<string name="action_settings">Settings</string>
<string name="hintTxtItem">Enter an item here ...</string>
<string name="lblBtnAdd">Add Item</string>
<string name="txtEmpty">List is empty</string>
<string name="delete_confirm">Are you sure you want to delete</string>
<string name="delete">Delete</string>
<string name="cancel">Cancel</string>
<string-array name="people">
<item>person 1</item>
<item>person 2</item>
<item>person 3</item>
<item>person 4</item>
<item>person 5</item>
<item>person 6</item>
</string-array>

Categories

Resources