I'm developing a material design app & for applying activity transition I have written the following code in my MainActivity.java
My MainActivity.java file's code:
public class MainActivity extends AppCompatActivity {
public Toolbar toolbar;
public TabLayout tabLayout;
public ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Call some material design APIs here
// enable transitions
getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
} else {
}
setContentView(R.layout.activity_main);
SpannableString s = new SpannableString("abc");
s.setSpan(new TypefaceSpan(this, "Pacifico.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle(s);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
customTabFont();
}
private void customTabFont() {
String fontPath = "fonts/Pacifico.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("Accept a Request");
tabOne.setTypeface(tf);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("Post a Request");
tabTwo.setTypeface(tf);
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new AcceptARequest(), "Accept a Request");
adapter.addFragment(new PostARequest(), "Post a Request");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#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_profile) {
// Check if we're running on Android 5.0 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Call some material design APIs here
getWindow().setExitTransition(new Explode());
Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileIntent, ActivityOptions
.makeSceneTransitionAnimation(this).toBundle());
} else {
// Implement this feature without material design
Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileIntent);
}
} else if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsIntent);
} else if (id == R.id.action_help) {
Intent helpIntent = new Intent(Intent.ACTION_SEND);
Intent chooser = Intent.createChooser(helpIntent, "Choose an app");
helpIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"help#abcxyz123.com"});
helpIntent.setType("message/rfc822");
startActivity(chooser);
} else if (id == R.id.action_faqs) {
Intent faqsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.abcxyz123.com/faqs"));
startActivity(faqsIntent);
} else if (id == R.id.action_about) {
Intent aboutIntent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(aboutIntent);
}
return super.onOptionsItemSelected(item);
}
}
After running the app, I'm getting following error:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content must be called before adding content.
I do not understand why am I getting this error when I have added the requestFeature() before adding the content?
Please let me know.
I'm new to StackOverflow, so please cooperate.
Thanks in advance.
Your activity extends AppCompatActivity which does extensive setup in its onCreate(). Call requestFeature() before calling super.onCreate().
Related
This is my mainactivity class and I am using my urls in the string. Anyone please tell me how to set wallpapers using multiple urls. I am using multiple urls to show in viewpager its working but I can't set wallpapers.
This is my main activity class.
I want to set wallpapers on floating button onclick listener
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private String[] imageUrls = new String[]{
"https://i.jj.cc/MGTTwJ7Q/Ant-Man-474b00d1-4bdc-3ea6-88a3-1702c46f061c.jpg",
"https://i.jj.cc/SKvKN1dt/fdg-min.jpg",
"https://i.jj.cc/fLSR37gW/uhd-antman18-min.jpg",
"https://i.jj.cc/Gt0hvBZF/uhd-antman7-min.jpg",
"https://i.jj.cc/ryWpMJrQ/Antman-And-The-Wasp-d4a753af-1dd1-4df2-aeb6-d39c732fd16a.jpg",
"https://i.jj.cc/RVLVnZGt/uhd-antman21-min.jpg",
"https://i.jj.cc/t4RRdGmM/Ant-man-and-the-wasp-a294bb80-e6f9-41c1-bf46-07af64e3e348.jpg",
"https://i.jj.cc/y8f1vpMY/Antman-d8033f49-b33c-4cd4-b3ca-651417df20da.jpg",
"https://i.jj.cc/yNkV5XKh/Antman-Abstract-HD-05ef2c84-e5d3-41e9-afa1-1400c315bf06.jpg",
"https://i.jj.cc/8C91VJk2/IMG-0139.jpg",
"https://i.jj.cc/Znh4CGdj/antman-70390c1f-2d63-41ea-a487-e34668167e7e.jpg",
"https://i.jj.cc/vTLM907y/antman-2fde23ba-9eac-4f11-acf7-b872b9b71121.jpg",
"https://i.jj.cc/66dBDpkP/Antman-d353b93b-5c57-4363-ad92-4a974423d2b5.jpg",
"https://i.jj.cc/rFMqcLcw/Antman-df2e8adb-b0a0-42b6-ade7-38d041349ed1.jpg",
"https://i.jj.cc/YCSkGfvc/Antman-32cb0b83-f4b6-4a24-854a-913b593c0291.jpg",
"https://i.jj.cc/zGPNnbhy/razakbaap49.jpg",
"https://i.jj.cc/tgZjDqd2/antman05-uhd.jpg"
};
private int indexOfImage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewPager viewPager = findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageUrls);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new MyPageChangeListener());
FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyPageChangeListener implements ViewPager.OnPageChangeListener {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
MainActivity.this.indexOfImage = i;
}
#Override
public void onPageScrollStateChanged(int i) {
}
}
}
This is my viewpager adapter class
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private String[] imageUrls;
ViewPagerAdapter(Context context, String[] imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
}
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
Picasso.with(context)
.load(imageUrls[position])
.fit()
.centerCrop()
.error(R.drawable.ic_error_outline_black_24dp)
.into(imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
}
Add permission in manifest
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
Add this AsyncTask class in your MainActivity
public class SetWallpaper extends AsyncTask<String, Void, Bitmap> {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
bitmap = Picasso.get().load(params[0]).get();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute (Bitmap result) {
super.onPostExecute(result);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
try {
wallpaperManager.setBitmap(result);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Wallpaper changed", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void onPreExecute () {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading image...");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
Then try
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SetWallpaper sw = new SetWallpaper();
sw.execute(imageUrls[indexOfImage])
}
});
I started off with a Navigation drawer activity and I added a recyclerView into the content_main.xml but I have been unable to implement the RecyclerView into the ManiActivity.java file.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
That is what my MainAcitity.java looks like when I haven't only implemented the NavigationView Activity.
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
And I also need this(the recyclerview) into my MainActivity.java There isn't room for both
This code below is my adapter class and the whole struggle is to add this to the MainActivity.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private List<String> mData = Collections.emptyList();
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
public MyRecyclerViewAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
// binds the data to the textview in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView myTextView;
public ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
You need to implement both NavigationView.OnNavigationItemSelectedListener and MyRecyclerViewAdapter.ItemClickListener interfaces on the MainActivity class. This way you would be able to call the adapter class for the Recycler view.Your code should look like this:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// data to populate the RecyclerView with
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add("Horse");
animalNames.add("Cow");
animalNames.add("Camel");
animalNames.add("Sheep");
animalNames.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvAnimals);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
In Java, a class can implement more than one interfaces and a class can only extend from one parent. Implementation of more than one interfaces eliminates multiple inheritance which is not allowed in Java.
For example:
ClassA implements ClassB, ClassC
Your edited code can be found here
Problem seems to be associated with Adapter class. I would like to see your code for adapter.
1. Make sure if count is not equal to zero.
2. Make sure you are inflating a proper view in adapter class.
3. The view you are inflating must have external layout Relative or Linear or Constraint.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
TabLayout tabLayout;
ViewPager viewPager;
NavigationView navigationView;
View navHeaderView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navHeaderView = navigationView.getHeaderView(0);
viewPager = (ViewPager) findViewById(R.id.viewPagerContainer);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
textViewNavigationName = (TextView)
navHeaderView.findViewById(R.id.textViewNavigationName);
textViewNavigationEmail = (TextView)
navHeaderView.findViewById(R.id.textViewNavigationEmail);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
Fragment_Home objFragment1 = new Fragment_Home();
fragmentTransaction.add(R.id.viewPagerContainer, objFragment1).addToBackStack("backkkkkkkkkkkkk");
fragmentTransaction.commit();
}
}
public class Fragment_Home extends Fragment
{
private static final String ARG_PAGE_KEY = "arg_page";
String nextPageToken;
String prevPageToken;
String pageToken;
int sizeOfPlaylist;
int sizeOfCurrentList;
int firstItemPosition;
MenuItem nextItem;
MenuItem lastItem;
LinearLayout linearLayoutProgress, linearLayoutNoConnection;
Button buttonReload;
RecyclerView recyclerViewVideos;
AllVideosAdapterR adapter;
TextView textViewProgress;
public static Fragment_Home newInstance(int pageNumber) {
Fragment_Home myFragment = new Fragment_Home();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE_KEY, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
LayoutInflater inflater1 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater1.inflate(R.layout.fragment_home, container, false);
getActivity().invalidateOptionsMenu();
findControls(view);
gettingList();
buttonReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gettingList();
}
});
return view;
}
public void findControls(View view)
{
recyclerViewVideos = (RecyclerView)view.findViewById(R.id.recyclerViewVideos);
linearLayoutProgress = (LinearLayout)view. findViewById(R.id.linearLayoutProgress);
textViewProgress = (TextView) view.findViewById(R.id.textViewProgress);
linearLayoutProgress.setVisibility(View.INVISIBLE);
linearLayoutNoConnection = (LinearLayout)view.findViewById(R.id.linearLayoutNoConnection);
linearLayoutNoConnection.setVisibility(View.INVISIBLE);
buttonReload = (Button)view.findViewById(R.id.buttonReload);
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public void setAdapter(List<Item> listItems) {
recyclerViewVideos.setLayoutManager(new
LinearLayoutManager(getActivity()));
adapter = new AllVideosAdapterR(getActivity(), listItems);
recyclerViewVideos.setAdapter(adapter);
}
public void showProgress(String message) {
textViewProgress.setText(message);
linearLayoutProgress.setVisibility(View.VISIBLE);
}
public void stopProgress() {
linearLayoutProgress.setVisibility(View.INVISIBLE);
}
public void gettingList() {
if (!isDeviceOnline()) {
linearLayoutNoConnection.setVisibility(View.VISIBLE);
} else {
linearLayoutNoConnection.setVisibility(View.INVISIBLE);
}
showProgress("Loading videos..");
Retrofit retrofit = newRetrofit.Builder().baseUrl(BaseUrls.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
WebApis call1 = retrofit.create(WebApis.class);
Call<ListResponse> call = call1.requestList();
call.enqueue(new Callback<ListResponse>() {
#Override
public void onResponse(Call<ListResponse> call, Response<ListResponse> response) {
System.out.println("size....................." + response.body().getItems().size());
setAdapter(response.body().getItems());
sizeOfPlaylist = response.body().getPageInfo().getTotalResults();
try {
nextPageToken = response.body().getNextPageToken();
prevPageToken = response.body().getPrevPageToken();
firstItemPosition = response.body().getItems().get(0).getSnippet().getPosition();
sizeOfCurrentList = response.body().getItems().size();
} catch (Exception e) {
Toast.makeText(getActivity(), "More pages not available", Toast.LENGTH_SHORT).show();
}
stopProgress();
}
#Override
public void onFailure(Call<ListResponse> call, Throwable t) {
stopProgress();
Toast.makeText(getActivity(), "Check your Network connection", Toast.LENGTH_LONG).show();
linearLayoutNoConnection.setVisibility(View.VISIBLE);
}
});
}
public void gettingNextList(String token) {
showProgress("Loading videos..");
Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrls.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
WebApis call1 = retrofit.create(WebApis.class);
Call<ListResponse> call = call1.requestNextList(token);
call.enqueue(new Callback<ListResponse>() {
#Override
public void onResponse(Call<ListResponse> call, Response<ListResponse> response) {
System.out.println("size....................." + response.body().getItems().size());
setAdapter(response.body().getItems());
try {
nextPageToken = response.body().getNextPageToken();
prevPageToken = response.body().getPrevPageToken();
firstItemPosition = response.body().getItems().get(0).getSnippet().getPosition();
sizeOfCurrentList = response.body().getItems().size();
} catch (Exception e) {
Toast.makeText(getActivity(), "More pages not available", Toast.LENGTH_SHORT).show();
}
stopProgress();
}
#Override
public void onFailure(Call<ListResponse> call, Throwable t) {
stopProgress();
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
}
});
}
public interface WebApis {
#GET(BaseUrls.GETTING_LIST)
Call<ListResponse> requestList();
#GET(BaseUrls.GETTING_LIST)
Call<ListResponse> requestNextList(#Query("pageToken") String pageToken);
}
}
I have an activity who load a list of data, this activity its a TabActivity with 3 Tabs, all tabs load a diferent data type.
But the data may be really a bunch of data, for that reason my activity may take a lot of time to show itself.
I start teh activity using
Intent intent = new Intent(MainActivity.this, PcapAnalisys.class);
startActivity(intent);
Then, when the activity is loading shows a black screen, and after a few seconds show the content properly.
There is a way on how to show a message like: "Loading activity... please wait" or something?
This is my code for a my TabActivity:
public class PcapAnalysis extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pcap_analysis);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mViewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//fab.setImageResource(R.drawable.ic_attach_file_white_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FileChooserDialog dialog = new FileChooserDialog(PcapAnalysis.this);
dialog.show();
dialog.addListener(new FileChooserDialog.OnFileSelectedListener() {
#Override
public void onFileSelected(Dialog source, File file) {
source.hide();
Toast.makeText(source.getContext(),
"File selected: " + file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
Log.i("Archivo seleccionado", file.getAbsolutePath());
new AsyncTask_load(PcapAnalysis.this, file.getAbsolutePath()).execute();
}
public void onFileSelected(Dialog source, File folder, String name) {
source.hide();
Toast.makeText(source.getContext(),
"File created: " + folder.getName() + "/" + name,
Toast.LENGTH_LONG).show();
}
});
}
});
new Task().execute();
}
#Override
public void recreate()
{
super.recreate();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
#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_pcap_analysis, 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);
}
/*public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pcap_analysis, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}*/
private class Task extends AsyncTask<Void, Integer, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(PcapAnalysis.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Procesando...");
pDialog.setCancelable(true);
pDialog.setMax(100);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager.setOffscreenPageLimit(3); //cuantas paginas se precargan
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
//publishProgress(progress);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
pDialog.dismiss();
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Fragment http = new HttpList();
private Fragment dns = new DnsList();
private Fragment ip = new IpList();
private Fragment resume = new ResumeList();
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position) {
case 0:
return http;
case 1:
return dns;
case 2:
return ip;
case 3:
return resume;
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "HTTP";
case 1:
return "DNS";
case 2:
return "RESOURCE IP";
case 3:
return "RESUME";
}
return null;
}
}
}
As you can see this activity use fragments to show the data, and each fragment has a for cicle to load the data (that is in a String array).
Also I use a AsyncTask trying to solve this problem, but is not working. Please help!
This is kind of hard to explain so I took screenshots of my problem.
So this is my MainActivity.java
I open the navigation drawer and click on Milestones which will bring me to Milestones.java
Here I am at Milestones.java fragment...
working fine for now...
Just how I want it to look.
But when we leave Milestones and go anywhere else and come back it will be messed up. So I will go to Kick Counter.
Here I am in my KickCounter.java fragment
Open navigation drawer and going back to Milestones...
So right now I have fragment Months0Through6 open with Milestones fragment. Some times Months0Through6 and Month12Plus fragments does not show up right away after coming back some times it does. What is always messed up at this point is the Months6Through12 fragment will never display again unless you restart the app. Also swapping between the three fragments is laggy after coming back but never on first view.
Here it is. Where did it go?
youtube video: https://www.youtube.com/watch?v=6yMYcluvqbs
Get Source Here: https://github.com/delaroy/RecyclerViewFragment
I got my code from this youtube video which is almost exactly identical but his MainActivity (which I made into my Milestones fragment) is an activity whereas I used a fragment so I was thinking that might have something to do with my problem.
Milestones.java
public class Milestones extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Milestones() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Milestones.
*/
// TODO: Rename and change types and number of parameters
public static Milestones newInstance(String param1, String param2) {
Milestones fragment = new Milestones();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_milestones, container, false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
//dont know if this will work
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager(), getContext());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for(int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
// Inflate the layout for this fragment
return rootView;
}
// not boiler plate
#Override
public void onResume() {
super.onResume();
}
// probably just adding extra menu dont need it
/*#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
//not boilerplate
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
//not boilerplate
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[]{"0-6 Months", "6-12 Months", "12+ Months"};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Months0Through6();
case 1:
return new Months6Through12();
case 2:
return new Months12Plus();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
return tabTitles[position];
}
public View getTabView(int position){
View tab = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
MilestonesAdapter.java
public class MilestonesAdapter extends RecyclerView.Adapter<MilestonesAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MilestonesAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MilestonesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
Just posting Months0Through6.java because the other two are exactly the same just different strings.
public class Months0Through6 extends android.support.v4.app.Fragment {
public Months0Through6() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MilestonesAdapter adapter = new MilestonesAdapter(new String[]{"Month 0 stuff", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements KickCounter.OnFragmentInteractionListener, MommyMetrics.OnFragmentInteractionListener, Milestones.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener {
Intent shareIntent;
String sharetext = "Hey check out mommy-info here at http://www.mommy-info.com";
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Connects to www.mommy-info.com
myWebView = (WebView)findViewById(R.id.webView_ID);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.mommy-info.com");
myWebView.setWebViewClient(new WebViewClient());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
//back button in navigation drawer logic
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
//back button in webView logic
else if(myWebView.canGoBack()){
myWebView.goBack();
}
else if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
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.kick_counter_ID) {
KickCounter kickCounter = new KickCounter();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, kickCounter).addToBackStack(null).commit();
} else if (id == R.id.nav_mommy_metrics) {
MommyMetrics mommyMetrics = new MommyMetrics();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, mommyMetrics).addToBackStack(null).commit();
} else if (id == R.id.nav_milestones) {
Milestones milestones = new Milestones();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, milestones).addToBackStack(null).commit();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "my app");
shareIntent.putExtra(Intent.EXTRA_TEXT, sharetext);
startActivity(Intent.createChooser(shareIntent, "share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
In Fragments you need to use getChildFragmentManager(), You are using same Fragment manager in the fragments as in Activity. Hope this will help
I've been reading a lot of questions and tutorials in regards to implementing a Navigation Drawer to change between Fragments. For this question, these implementations are not wanted as I wish to change from one activity, to the next.
I've implemented a custom Sidebar Adaptor with extends ArrayAdapter<String>. This allows to to implement my own styling to my navigation drawer. See the first code snippet below.
public class SidebarAdaptor extends ArrayAdapter<String> {
Context context;
int layoutResourceId;
String data[] = null;
public SidebarAdaptor(Context context, int layoutResourceId, String[] data)
{
// Initiate the ArrayAdapter
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ControlHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ControlHolder();
TextView control = (TextView)row.findViewById(R.id.textItem);
holder.control = control;
row.setTag(holder);
}
else
{
holder = (ControlHolder)row.getTag();
}
String text = data[position];
holder.control.setText(text);
return row;
}
static class ControlHolder
{
TextView control;
}
}
This adapter is then set in the onCreate function in my MainActivity class. See below.
private void customiseSidebar() {
SidebarAdaptor sidebarAdaptor = new SidebarAdaptor(
this,
R.layout.side_bar_custom_row,
new String[]{"Login", "Offline Access", "Register", "Forgotten Password"}
);
ListView listView1 = (ListView) findViewById(R.id.navList);
listView1.setAdapter(sidebarAdaptor);
listView1.setOnItemClickListener(new DrawerItemClickListener());
}
The DrawerItemClickListener class then holds what activity to switch to once the user pressed any of the options in the Navigation Drawer. See the final code snippet below.
package ap.classes;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import ap.ForgottenPassword;
import apMainActivity;
import ap.OfflineAccess;
import ap.RegisterAccount;
public 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) {
switch(position)
{
case 0:
Intent intent = new Intent(MainActivity.this, OfflineAccess.class);
startActivity(intent);
break;
case 1:
Intent intent = new Intent(MainActivity.this, RegisterAccount.class);
startActivity(intent);
break;
case 2:
Intent intent = new Intent(MainActivity.this, ForgottenPassword.class);
startActivity(intent);
break;
}
}
Now I seem to be having three quite substantial issues:
The first being the following error message: MainActivity is not an enclossing class
The second states that it; Cannont resolve method startActivity in android.content.Intent
The final issue is, as soon as I click anything in the NavigationDrawer, the drawer then closes without any keypresses being registered.
Thank you Stackoverflow.
First fix first two issues:
The first being the following error message: MainActivity is not an enclossing class
The second states that it; Cannont resolve method startActivity in android.content.Intent
According to code you provided you are not in the scope of the Activity class when making call
Intent intent = new Intent(MainActivity.this, OfflineAccess.class);
startActivity(intent);
above tells compiler to call method DrawerItemClickListener.startActivity(Intent intent), and there is no such method. Instead you should pass instance of an activity and call its startActivty method.
Second one MainActivity is not an enclossing class error is thrown because of usage MainActivity.this instead of passing instance of context.
To sum up you could do:
public class DrawerItemClickListener implements ListView.OnItemClickListener {
private Activity mActivity;
public DrawerItemClickListener(Activity activity){
mActivity = activity;
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
switch(position)
{
case 0:
Intent intent = new Intent(mActivity, OfflineAccess.class);
mActivity.startActivity(intent);
break;
/.../
}
}
Yes i had faced similar problem.While Fragments with navigation drawer it will be easy but using Activity. You must create a Custom Navigation Drawer. I give my idea.enter code here
public class DrawerItemClickListener extends AppCompatActivity{
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private List<DrawerList> drawerListList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentView());
drawerListList = new ArrayList<>();
mDrawerList = (ListView) findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
}
#Override
protected void onPostResume() {
super.onPostResume();
}
protected abstract int getContentView();
private void addDrawerItems() {
drawerListList.add(new DrawerList("1", R.drawable.1));
drawerListList.add(new DrawerList("2", R.drawable.2));
drawerListList.add(new DrawerList("3", R.drawable.3));
drawerListList.add(new DrawerList("4", R.drawable.4));
drawerListList.add(new DrawerList("5", R.drawable.5));
CustomDrawerAdapter adapter = new CustomDrawerAdapter(this, R.layout.list_view_menu, drawerListList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (id == 0) {
intent = new Intent(DrawerItemClickListener .this, FirstActivity.class);
startActivity(intent);
onDrawerClose();
} else if (id == 1) {
intent = new Intent(DrawerItemClickListener .this, SecondActivity.class);
startActivity(intent);
onDrawerClose();
} else if (id == 2) {
intent = new Intent(DrawerItemClickListener .this, ThirdActivity.class);
startActivity(intent);
onDrawerClose();
} else if (id == 3) {
intent = new Intent(DrawerItemClickListener .this, FouthActivity.class);
startActivity(intent);
onDrawerClose();
}
}
}
});
}
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("Navigation!");
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);
}
public void onDrawerClose() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
onBackPressed();
}
}
#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 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();
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And Custom Adapter is below
public class CustomDrawerAdapter extends ArrayAdapter<DrawerList> {
private Context context;
private List<DrawerList> drawerItemList;
private int layoutResID;
public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerList> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_itemName);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerList dItem = this.drawerItemList.get(position);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(dItem.getMenuImage()));
drawerHolder.ItemName.setText(dItem.getMenuName());
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
}
}
And you extend it from each activity like
public class FirstActivity extends DrawerItemClickListener {
..
}
And also Listview Added in each xml layout.
Hope It will be helpful.