Good day. I need to change text color in of list view with the switch of a button click. List view with custom adapter and custom layout. Text view in newsitemlist_layout.xml inflated with adapter normal it works fine but in fragment give error "Adaptor.setTextColor(int)' on a null object reference." The problem is that adapter is initialized in fragment and switch or button in main activity if I implement change text color in fragment it works but not in main activity. So now need on click in main activity and change text color in the adapter. Is there any way to do this. Please help.
Main activity.java
NewsAdaptor adaptor;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick ( View view ) {
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#SuppressLint("ResourceAsColor")
#Override
public void onCheckedChanged ( CompoundButton buttonView,
boolean isChecked ) {
adaptor.setTextColor(Color.GREEN);
adaptor.notifyDataSetChanged();
} else {
adaptor.setTextColor(Color.RED);
adaptor.notifyDataSetChanged();
}
}
});
public boolean onNavigationItemSelected ( MenuItem item ) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
FeagmentA expressMain = new FeagmentA ();
FragmentManager fragmentManager= getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,expressMain.getTag())
.commit();
} else if (id == R.id.nav_gallery) {
Jungmain expressMain = new Jungmain();
FragmentManager fragmentManager= getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,expressMain.getTag())
.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
Fragment.java
public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
ListView lvRss;
ArrayList<NewsItem> newsItemsList;
NewsAdaptor adapter;
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_a, container, false);
lvRss = (ListView) view.findViewById(R.id.fragmentalistview);
newsItemsList = new ArrayList <>();
new n2().execute();
return view;
}
private class n2 extends AsyncTask<Integer,Void,Intent> {
#Override
protected Intent doInBackground ( Integer... integers ) {
try {
Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/pakistan/rss.xml").ignoreHttpErrors(true).get();
Elements itemElements = document.getElementsByTag("item");
for (int i = 0; i < itemElements.size(); i++) {
Element item = itemElements.get(i);
NewsItem newsItem = new NewsItem();
newsItem.setImagePath(item.child(5).getElementsByTag("media:thumbnail").first().attr("url"));
newsItem.setDate(rem1(item.child(4).text()));
newsItem.setTitle(item.child(0).text());
newsItem.setLink(item.child(3).text());
newsItemsList.add(newsItem);
Collections.sort(newsItemsList, new Comparator<NewsItem>() {
#Override
public int compare ( NewsItem o1, NewsItem o2 ) {
return o1.dateInMilliSec > o2.dateInMilliSec ? -1 :
o1.dateInMilliSec < o2.dateInMilliSec ? 1 : 0;
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
getActivity(). runOnUiThread(new Runnable() {
#Override
public void run () {
adapter = new NewsAdaptor(getContext(), newsItemsList);
lvRss.setAdapter(adapter);
}
});
return null;
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
NewsAdapter.java
public class NewsAdaptor extends BaseAdapter {
TextView tvtitle;
Context context;
private int color;
public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
this.context = context;
this.newsList = newsList;
this.color = Color.RED;
}
ArrayList <NewsItem> newsList;
#Override
public int getCount () {
return newsList.size();
}
#Override
public Object getItem ( int position ) {
return newsList.get(position);
}
#Override
public long getItemId ( int position ) {
return 0;
}
#SuppressLint("ResourceAsColor")
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
if (convertView == null) {
convertView = View.inflate(context, R.layout.newsitemlist_layout, null);
}
NewsItem currentNews = newsList.get(position);
tvtitle = (TextView) convertView.findViewById(R.id.textView1id);
tvtitle.setText(currentNews.getTitle());
tvtitle.setTextColor(color);
return convertView;
}
public void setTextColor(int color) {
this.color = color;
}
}
NewsItem.java
public class NewsItem implements Serializable {
String title;
public String getTitle () {
return title;
}
public void setTitle ( String title ) {
this.title = title;
}
#Override
public String toString() {
return title;
}
NewsItemlist.layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp">
<TextView
android:id="#+id/textView1id"
android:layout_width="237dp"
android:layout_height="83dp"
android:layout_alignEnd="#+id/pubDateid"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/pubDateid"
android:ellipsize="end"
android:gravity="right"
android:text="News TITLE"
android:textStyle="bold" />
Try this
Add this code in MainActivity Click event:
Fragment frag = getSupportFragmentManager().findFragmentById(R.id.containerview);
if(frag instanceof FragmentA )
{
((FragmentA ) frag).adapter.setTextColor(Color.RED);
((FragmentA ) frag).adapter.notifyDataSetChanged();
}
EDITED
Change this line
fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,expressMain.getTag())
.commit();
To
fragmentManager.beginTransaction().replace(R.id.containerview,expressMain,"TAG_NAME").addToBackStack("TAG_NAME").commit();
Then find fragment from fragmentmanager in activity class like below:
Fragment frag = getSupportFragmentManager().findFragmentByTag("TAG_NAME");
Related
Good day How can I call a fragment when the users will click the card inside MyAdapter class. I want to replace view from the adapter. I am using recyclerview wants to perform click event using the view from my row layout.
Like for example when the user clicks the card it will open a fragment and it will show more data. Hope you can help me guys.
This is my main fragment
AccountsFragment
ReceivableFragment
LoanAppFragment
Those fragments hold different data. when the user clicks the cards inside that fragment it will call another fragment the SLDTLFragment.
Btw this MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Datas> mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
public CardView mCardView;
public TextView account_type;
public TextView accnt_description;
public TextView balance_label;
public TextView account_balance;
public MyViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
account_type = (TextView) v.findViewById(R.id.lblShareCapital);
balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);
accnt_description = (TextView) v.findViewById(R.id.sl_desc);
account_balance = (TextView) v.findViewById(R.id.actual_balance);
}
}
public MyAdapter(List<Datas> myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
//holder.account_type.setText(mDataset[position]);
Datas datas = mDataset.get(position);
holder.accnt_description.setText(datas.getSL_DESC());
holder.account_balance.setText(datas.getACTUAL_BALANCE());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String sl_desc = mDataset.get(position).getSL_DESC();
// String actual_balance = mDataset.get(position).getACTUAL_BALANCE();
String sle = mDataset.get(position).getSLE();
String slc = mDataset.get(position).getSLC();
String slt = mDataset.get(position).getSLT();
String ref_no = mDataset.get(position).getREF();
Log.d("CardView Clicked", "sle code: " + sle);
Log.d("CardView Clicked", "slc code: " + slc);
Log.d("CardView Clicked", "slt code: " + slt);
Log.d("CardView Clicked", "ref no: " + ref_no);
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
AccountsFragment.java
public class AccountsFragment extends Fragment {
private SQLiteHandler db;
public AccountsFragment() {
// 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_accounts, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
SQLiteHandler db = new SQLiteHandler(getActivity());
MyAdapter adapter = new MyAdapter(db.getUserSLDetails());
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
ReceivableFragment.java
public class ReceivableFragment extends Fragment {
public ReceivableFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_receivable, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
SQLiteHandler db = new SQLiteHandler(getActivity());
MyAdapter adapter = new MyAdapter(db.getUserSLARLoans());
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView nav_header_name;
private TextView nav_header_email;
public TextView txtLogOut;
private SQLiteHandler db;
private SessionManager session;
private Timer timer;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Will replace the activity_main.xml to relativelayout_for_fragment.xml
if (savedInstanceState == null) {
AccountsFragment f1= new AccountsFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.relativelayout_for_fragment, f1);// relativelayout_for_fragment is inside the content_main.xml
fragmentTransaction.commit();
}
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);
View header=navigationView.getHeaderView(0);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
txtLogOut = (TextView) findViewById(R.id.nav_logout_menu);
int id = item.getItemId();
if (id == R.id.nav_deposit) {
// Handle the preference action
AccountsFragment accounts= new AccountsFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relativelayout_for_fragment, accounts)
.commit();
Toast.makeText(MainActivity.this, "Deposit Accounts", Toast.LENGTH_SHORT).show();
}else if (id == R.id.nav_receivable) {
// Handle the Loan application();
ReceivableFragment receivable= new ReceivableFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relativelayout_for_fragment, receivable)
.commit();
Toast.makeText(MainActivity.this, "AR and Loan Accounts", Toast.LENGTH_SHORT).show();
}else if (id == R.id.nav_apply_loan_menu) {
// Handle the Loan application();
LoanAppFragment loan_app= new LoanAppFragment();
FragmentManager manager= getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.relativelayout_for_fragment, loan_app)
.commit();
Toast.makeText(MainActivity.this, "This module is under developement", Toast.LENGTH_SHORT).show();
}else if (id == R.id.nav_logout_menu) {
// Handle the About action
logoutUser();
//Toast.makeText(MainActivity.this, "successfully Logout", Toast.LENGTH_LONG).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
nav_header_name = (TextView) header.findViewById(R.id.nav_name);
nav_header_email = (TextView) header.findViewById(R.id.nav_email);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
//Fetching user details from SQLite
HashMap<String, String> user = db.getUserDetails();
String username = user.get("username");
String email = user.get("email");
//Displaying the user info in nav_header_main.xml
nav_header_name.setText(username);
nav_header_email.setText(email);
}
#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);
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
db.deleteUserSLDTL();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
#Override
protected void onPause() {
super.onPause();
timer = new Timer();
Log.i("Main", "Invoking logout timer");
LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
timer.schedule(logoutTimeTask, 30000); // auto logout in 30secs inactivity
Log.i("Main", "Log out user due to inactivity");
}
#Override
protected void onResume() {
super.onResume();
if (timer != null) {
timer.cancel();
Log.i("Main", "cancel timer");
timer = null;
}
}
private class LogOutTimerTask extends TimerTask {
#Override
public void run() {
session.setLogin(false);
db.deleteUsers();
db.deleteUserSLDTL();
//redirect user to login screen
Intent i = new Intent(MainActivity.this, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
}
You need to use Listener/Callback pattern to inform your Activity or Fragment where the Adapter is used. Do not directly call a Fragment or activity inside of the Adapter because it will defeat the purpose of the Adapter. Adapter should only be used to show the data.
To implement the pattern, first create the interface and constructor to set the listener in your Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
...
private List<Datas> mDataset;
private ClickListener mListener;
public interface ClickListener {
void onItemClicked(YourData yourData);
}
public MyAdapter(List<Datas> myDataset, ClickListener listener) {
mDataset = myDataset;
mListener = listener;
}
...
}
Second, whenever there is a click of the item data, tell the listener with the following code in your Adapter:
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
...
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String sl_desc = mDataset.get(position).getSL_DESC();
// String actual_balance = mDataset.get(position).getACTUAL_BALANCE();
// String sle = mDataset.get(position).getSLE();
// String slc = mDataset.get(position).getSLC();
// String slt = mDataset.get(position).getSLT();
// String ref_no = mDataset.get(position).getREF();
// Simplify the above to a pojo. We assume the pojo is YourData
YourData data = new YourData();
// set the data from above.
mListener.onItemClicked(yourData);
});
}
Third, you need to set the listener in your Activity/Fragment which using the Adapter with:
MyAdapter.ClickListener listener = new MyAdapter.ClickListener() {
#Override
public void onItemClicked(YourData yourData) {
// Do something with the data here.
}
};
MyAdapter adapter = new MyAdapter(db.getUserSLARLoans(), listener);
rv.setAdapter(adapter);
You need to handle the data in your listener inside the onItemClicked() method above.
try to pass getFragmentManager using constructor and then replace the view with container view in your item row.
//constructor
public MyAdapter(FragmentManager fragment, List<Datas> myDataset) {
mDataset = myDataset;
mFragment = fragment;
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView mCardView;
public TextView account_type;
public TextView accnt_description;
public TextView balance_label;
public TextView account_balance;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
account_type = (TextView) v.findViewById(R.id.lblShareCapital);
balance_label = (TextView) v.findViewById(R.id.lblAvailableBalance);
accnt_description = (TextView) v.findViewById(R.id.sl_desc);
account_balance = (TextView) v.findViewById(R.id.actual_balance);
mCardView.setOnClickListener(this)
}
#Override
public void onClick(View view){
mFragment.beginTransaction().replace(R.id.containerRow,new MyFragment()).commit();
}
}
//note this is not tested code.
I have a MainActivity with two fragments. The second fragment has RecyclerView. There is TextView ( lesson name) and ImageView(show lesson status, if it is done or not) in RecyclerView . When you click TextView, it calls another Activity with lesson. After you make the lesson you will go back to MainActivity. After that lessons ImageView will be changed from nothing to resourse 'ic_lessondone'. Also there is a menu in MainActivity. Menu have item 'Reset lessons'. When you press 'Reset lessons' all ImageViews wont show any images. So there are two problems. 1) if I do, for example , only 6th lesson. I will have image 'lessondone'. When i press 'Reset lessons' image will disappear. But when i go back to menu again and press 'Reset lessons', Image will appear again and rise to previous lesson ( 5th). 2) If i switch off display, image will also appear to previous lessons till to 0th.
Its seems i have a problem with onResume.
Help me please.
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null)
{
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
{
setupViewPager(viewPager);
}
// Круглая кнопка
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Картинки для табов
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
switch (AppCompatDelegate.getDefaultNightMode())
{
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
}
return super.onOptionsItemSelected(item);
}
private void setNightMode(#AppCompatDelegate.NightMode int nightMode)
{
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11)
{
recreate();
}
}
private void setupViewPager(ViewPager viewPager)
{
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Fragment(), "");
adapter.addFragment(new LessonsListFragment(), "");
viewPager.setAdapter(adapter);
}
// Главное меню
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
if (menuItem.getTitle().equals("Reset lessons"))
{
// Обнуляем файл с рузультатами уроков
LessonsListFragment.sLessonsPref.edit().clear().commit();
// Перерисовываем весь писок уроков
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
// Получаем конкретный фрагмент
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
// Количество фрагментов для viewpager (2)
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
}
Fragment
public class LessonsListFragment extends Fragment
{
// Уроки
// static private Map<String,?> mLessonsKeys ;
static SharedPreferences sLessonsPref;
static RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
loadSharedPreferenses();
rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
// Загружаем список пройденных уроков
public void loadSharedPreferenses()
{
sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
}
// Количество строк в листе
private void setupRecyclerView(RecyclerView recyclerView)
{
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
}
// Задаем Строки
private List<String> getRandomSublist(String[] array, int amount)
{
ArrayList<String> list = new ArrayList<>(amount);
//Random random = new Random();
while (list.size() < amount)
{
list.add(array[list.size()]);
}
return list;
}
//Отработка перерисования окна, при возврате к ней
#Override
public void onResume()
{
super.onResume();
//loadSharedPreferenses();
//Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
if (rv.getAdapter() != null)
{
rv.getAdapter().notifyDataSetChanged();
}
}
// Адаптер
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
{
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
public static class ViewHolder extends RecyclerView.ViewHolder
{
// Номер урока, передается в webactivity
public int mLessonNumber;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view)
{
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString()
{
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position)
{
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
{
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
// Создаем холдер с полезной нагрузкой
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
//Создаем список уроков
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.mLessonNumber = position + 1;
// Увеличиваем позицион на 1 что не было 0 урока
holder.mTextView.setText((position + 1) + " " + mValues.get(position));
// Если урок пройден
String finished = sLessonsPref.getString((position + 1) + "", "");
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
//.load(Cheeses.getRandomCheeseDrawable())
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
holder.mTextView.setTextColor(R.color.black);
// holder.mImageView.setVisibility(View.GONE);
}
// Вызов WebActivity
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Context context = v.getContext();
Intent intent = new Intent(context, WebActivity.class);
// Передаем вебвью номер урока и запускаем ее
intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
context.startActivity(intent);
}
});
}
// Определяем количество выводимых строк
#Override
public int getItemCount()
{
return mValues.size();
}
}
}
Implement a reset() method in the adapter that mark all items as "not done" and then try:
LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();
instead of:
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
inside onNavigationItemSelected.
Also, you shouldn't be using static variables (like static RecyclerView rv), use private vars with getters
The problem was in else statement. I added there this code, and now its ok. notifydatachanged work correctly from navigationview
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
Glide.with(holder.mImageView.getContext()).load(R.color.white)
.fitCenter()
.into(holder.mImageView);
holder.mTextView.setTextColor(R.color.black);
}
I'm new to Android and I started building a "Navigation Drawer Activity" project. I added a TabLayout and ViewPager to my activity_main.xml and now I can swipe between different lists. When I click an item in a list, it calls onListFragmentInteraction in my MainActivity.java. I tried the code below to dynamically add a Detail fragment when a user clicks an item in the list, but I get this error. My MainActivity class does "implement CustomerFragment.OnListFragmentInteractionListener"
First, is my attempt at showing a detail fragment inside a ViewPager correct? Would the code I am attempting below add a fragment in the current tab?
Secondly, does anyone know why I am getting this error?
Thanks so much!
Error:
java.lang.RuntimeException: com.myproject.android.MainActivity#186e12d
must implement OnFragmentInteractionListener
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, TabLayout.OnTabSelectedListener, CustomerFragment.OnListFragmentInteractionListener, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private TabLayout tabLayout;
private ViewPager viewPager;
private Pager adapter;
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) { }
#Override
public void onTabReselected(TabLayout.Tab tab) { }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Customers"));
tabLayout.addTab(tabLayout.newTab().setText("Jobs"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(this);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FirebaseMessaging.getInstance().subscribeToTopic("global");
String token = FirebaseInstanceId.getInstance().getToken();
// Check Google Play Services
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();
// test
Date d = new Date();
DbHandler dbHandler = new DbHandler(this, null, null, 1);
Customer customer = new Customer(1, 1, 1, 1, "Test", "Test", "Test", false, d, 1, d, 1);
dbHandler.addCustomer(customer);
}
#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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
startActivity(new Intent(this, LoginActivity.class));
} else if (id == R.id.nav_gallery) {
startActivity(new Intent(this, SyncActivity.class));
} 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 onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Customer List Fragment:
public class CustomerFragment extends Fragment {
private OnListFragmentInteractionListener mListener;
public CustomerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
SearchView sv = (SearchView) view.findViewById(R.id.searchview);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
// Adapter
rv.setLayoutManager(new LinearLayoutManager(view.getContext()));
final CustomerAdapter adapter = new CustomerAdapter(getCustomers(), mListener);
rv.setAdapter(adapter);
// Search
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
//adapter.getFilter().filter(query);
return false;
}
});
return view;
}
private ArrayList<Customer> getCustomers() {
DbHandler dbHandler = new DbHandler(this.getActivity(), null, null, 1);
ArrayList<Customer> customers = dbHandler.getCustomers();
return customers;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction(Customer customer);
}
}
Customer Adapter:
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {
private final List<Customer> mValues;
private final OnListFragmentInteractionListener mListener;
public CustomerAdapter(List<Customer> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_customer, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Customer customer = mValues.get(position);
holder.mItem = customer;
holder.mIdView.setText(String.valueOf(customer.getId()));
holder.mContentView.setText(customer.getCompanyName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public Customer mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
UPDATE: It looks like I needed to add both onListFragmentInteraction AND onFragmentInteraction. The first is for the CustomerListFragment and the 2nd is for the CustomerDetailFragment.
And to get the CustomerDetailFragment working with the tabs, I followed this and got it working:
https://medium.com/#nilan/separate-back-navigation-for-a-tabbed-view-pager-in-android-459859f607e4#.lrjeexdcp
#Override
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
You need to put
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
Inside your MainActivity class instead of outside of it.
If that's not actually how your code is, edit your answer to break up the blocks to accurately represent how your code is built and include your interfance inside the fragment for the listener. You also may need the #Override tag above the onListFragmentInteraction implementation
Edit
As I mentioned above you need to put the #Override tag above the onListFragmentInteraction implementation, look at every other listener implementation you already have.
I want to start intent from ViewHolder class to the Fragment of Navigation Drawer Fragment class. Please see the code below.
public class LinearViewHolder extends RecyclerView.ViewHolder {
public TextView countryName;
public ImageView countryPhoto;
public Context context;
public LinearViewHolder(View v) {
super(v);
context = itemView.getContext();
countryName = (TextView) itemView.findViewById(R.id.country_name);
countryPhoto = (ImageView) itemView.findViewById(R.id.country_photo);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos == 0) {
//here we go to ActivityFragment class???
} else if (pos == 1) {
//here we go to ActivityFragment class???
} else if (pos == 2) {
//here we go to ActivityFragment class???
} else if (pos == 3) {
} else if (pos == 4) {
} else if (pos == 5) {
}
}
});
}
}
And the FragmentActivity.class code is this below!
public class ActivityFragment extends Fragment {
private List<ActivitySetData> history;
RecyclerView recList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.actvity_toolbar, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar_two);
setSupportActionBar(toolbar);
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) v.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) v.findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
try {
Glide.with(this).load(R.color.light_blue).into((ImageView) v.findViewById(R.id.backdrop));
} catch (Exception e) {
e.printStackTrace();
}
recList = (RecyclerView) v.findViewById(R.id.recycler_view);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
initializeData();
initializeAdapter();
return v;
}
private void initializeData() {
history = new ArrayList<>();
history.add(new ActivitySetData(R.color.light_blue, "Getting knowing the Activity", getString(R.string.activity_first)));
history.add(new ActivitySetData(R.color.light_blues1, "Navigation Through Activities", getString(R.string.activity_second)));
history.add(new ActivitySetData(R.color.light_blues2, "Tasks", getString(R.string.activity_third)));
history.add(new ActivitySetData(R.color.light_blues3, "The Talkback Stack", getString(R.string.activity_four)));
history.add(new ActivitySetData(R.color.light_blues4, "Activity Life Cycle", getString(R.string.activity_five)));
history.add(new ActivitySetData(R.color.light_blues6, "Activity Life Cycle Methods", getString(R.string.activity_six)));
}
private void initializeAdapter() {
ActivityAdapter adapter = new ActivityAdapter(history);
recList.setAdapter(adapter);
}
private void setSupportActionBar(Toolbar toolbar) {
}
}
And the code of my Parent MainActivity.class is below
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Defining Variables
private NavigationView navigationView;
private DrawerLayout drawerLayout;
String showFragmentCheck;
private TextView tool;
FragmentManager mFragmentManager;
LinearLayout linearLayoutSelectLocation;
private TextView textViewCancel;
private TextView textViewLike;
private TextView textViewShare;
private ImageView ic_short;
private FloatingActionButton fab;
private static final String SHOWCASE_ID = "sequence example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
register_view();
presentShowcaseSequence(); // one second delay
textViewLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=app.mytutoandroid"));
startActivity(browserIntent);
}
});
textViewShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=app.mytutoandroid");
startActivity(intent);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
textViewCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutSelectLocation.setVisibility(View.INVISIBLE);
}
});
ic_short.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UiShortcuts.class);
// intent.putExtra("lastFragment","News");
startActivity(intent);
finish();
}
});
mFragmentManager = getSupportFragmentManager();
showFragmentCheck = getIntent().getStringExtra("checkFragment");
if (showFragmentCheck == null) {
showChildFragment("Getting Started");
} else {
showChildFragment(showFragmentCheck);
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawerLayout.closeDrawers();
showChildFragment(menuItem.getTitle().toString());
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name,
R.string.app_name);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
public void register_view() {
tool = (TextView) findViewById(R.id.toolbar_title);
tool.setOnClickListener(this);
textViewLike = (TextView) findViewById(R.id.textViewLike);
textViewShare = (TextView) findViewById(R.id.textViewShare);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
textViewCancel = (TextView) findViewById(R.id.textViewCancel);
linearLayoutSelectLocation = (LinearLayout) findViewById(R.id.linearLayoutSelectLocation);
ic_short = (ImageView) findViewById(R.id.choose_short);
ic_short.setOnClickListener(this);
}
public void showChildFragment(String fragmentTitle) {
if (fragmentTitle.equals("Activity")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Activity");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ActivityFragment()).commit();
} else if (fragmentTitle.equals("Getting Started")) { // on 2nd item in the menu, do somethin
tool.setText("Android Development");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new MainFragment()).commit();
} else if (fragmentTitle.equals("Services")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Services");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ServicesFragment()).commit();
} else if (fragmentTitle.equals("Content Provider")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Content Provider");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ContentFragment()).commit();
} else if (fragmentTitle.equals("BroadCast Receiver")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to BroadCast Receiver");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new BroadCastFragment()).commit();
} else if (fragmentTitle.equals("Networking")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Networking");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new NetworkingFragment()).commit();
} else if (fragmentTitle.equals("Android Manifest")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Manifests");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ManiFragment()).commit();
} else if (fragmentTitle.equals("References")) { // on 2nd item in the menu, do somethin
tool.setText("References");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new References()).commit();
} else {
showChildFragment("Getting Started");
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.choose_short || v.getId() == R.id.toolbar_title) {
presentShowcaseSequence();
}
}
private void presentShowcaseSequence() {
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(500); // half second between each showcase view
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, SHOWCASE_ID);
sequence.setOnItemShownListener(new MaterialShowcaseSequence.OnSequenceItemShownListener() {
#Override
public void onShow(MaterialShowcaseView itemView, int position) {
Toast.makeText(itemView.getContext(), "Item #" + position, Toast.LENGTH_SHORT).show();
}
});
sequence.setConfig(config);
sequence.addSequenceItem(ic_short, "Shortcut for Android topics\nFind the Android Content with details.", "GOT IT");
sequence.start();
}
}
In Adapter
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos == 0) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("checkFragment", "ActivityFragment");
context.startActivity(intent);
} else if (pos == 1) {
//same as above
} else if (pos == 2) {
///same as above
} else if (pos == 3) {
} else if (pos == 4) {
} else if (pos == 5) {
}
}
});
In MainActivity
mFragmentManager = getSupportFragmentManager();
showFragmentCheck = getIntent().getStringExtra("checkFragment");
if (showFragmentCheck == null) {
showChildFragment("Getting Started");
} else {
if (showFragmentCheck.equalsIgnoreCase("ActivityFragment")) {
showChildFragment("Activity");
}else
{
showChildFragment(showFragmentCheck);
}
}
try with this way or try with this link Click Here to more
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Dependency:-
compile 'com.android.support:recyclerview-v7:21.0.0-rc1'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
}
public class ContactInfo {
protected String name;
protected String surname;
protected String email;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String EMAIL_PREFIX = "email_";
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vEmail;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vTitle = (TextView) v.findViewById(R.id.title);
}
}
public class ContactAdapter extends
RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
...
}
}
I am attempting to use Kanytu's android-material-drawer-template to implement a Navigation Drawer that meets Google's material design guidelines. The issue I'm facing is: Upon selecting a fragment to transition to from the navigation drawer, the selected fragment will successfully replace the current fragment within the 'container' FrameLayout. However, the HomeAsUp Indicater will display a "Back" navigation arrow in the Toolbar, rather than the Hamburger Icon needed to open the Navigation Drawer.
From what I can gather, this is due to the ActionBarDrawerToggle becoming out of sync when the fragments are being swapped. Assuming this to be the issue (I'm open for suggestions), how could I call .syncState() within the NavigationActivity fragments on the current ActionBarDrawerToggle?
public class NavigationActivity extends ActionBarActivity implements NavigationDrawerCallbacks {
private Toolbar mToolbar;
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate( #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
if (findViewById(R.id.container) != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Toast.makeText(this, "Menu item selected -> " + position, Toast.LENGTH_SHORT).show();
if (position == 0) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, new UserFragment());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(getString(R.string.user_profile_title));
}
}
if (position == 1) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, new TeamFragment());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(getString(R.string.team_profile_title));
}
}
if (position == 2) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.container, new ExploreFragment());
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(getString(R.string.explore_title));
}
}
}
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
}
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.ViewHolder> {
private List<NavigationItem> mData;
private NavigationDrawerCallbacks mNavigationDrawerCallbacks;
private int mSelectedPosition;
private int mTouchedPosition;
private boolean isClick = false;
public NavigationDrawerAdapter(List<NavigationItem> data) {
mData = data;
}
public NavigationDrawerCallbacks getNavigationDrawerCallbacks() {
return mNavigationDrawerCallbacks;
}
public void setNavigationDrawerCallbacks(NavigationDrawerCallbacks navigationDrawerCallbacks) {
mNavigationDrawerCallbacks = navigationDrawerCallbacks;
}
#NotNull
#Override
public NavigationDrawerAdapter.ViewHolder onCreateViewHolder( #NotNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.drawer_row, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder( #NotNull NavigationDrawerAdapter.ViewHolder viewHolder, final int i) {
viewHolder.textView.setText(mData.get(i).getText());
viewHolder.textView.setCompoundDrawablesWithIntrinsicBounds(mData.get(i).getDrawable(), null, null, null);
viewHolder.itemView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, #NotNull MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchPosition(i);
return false;
case MotionEvent.ACTION_CANCEL:
touchPosition(-1);
return false;
case MotionEvent.ACTION_MOVE:
return false;
case MotionEvent.ACTION_UP:
touchPosition(-1);
return false;
}
return true;
}
}
);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mNavigationDrawerCallbacks != null)
mNavigationDrawerCallbacks.onNavigationDrawerItemSelected(i);
}
}
);
//TODO: selected menu position, change layout accordingly
if (mSelectedPosition == i || mTouchedPosition == i) {
viewHolder.itemView.setBackgroundColor(viewHolder.itemView.getContext().getResources().getColor(R.color.nav_selected));
} else {
viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);
}
}
private void touchPosition(int position) {
int lastPosition = mTouchedPosition;
mTouchedPosition = position;
if (lastPosition >= 0)
notifyItemChanged(lastPosition);
if (position >= 0)
notifyItemChanged(position);
}
public void selectPosition(int position) {
int lastPosition = mSelectedPosition;
mSelectedPosition = position;
notifyItemChanged(lastPosition);
notifyItemChanged(position);
}
#Override
public int getItemCount() {
return mData != null ? mData.size() : 0;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder( #NotNull View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_name);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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/activity_navigation_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:name="com.example.appnamehere.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREFERENCES_FILE = "my_app_settings"; //TODO: change this to your file
#Nullable
private NavigationDrawerCallbacks mCallbacks;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private DrawerLayout mDrawerLayout;
public ActionBarDrawerToggle mActionBarDrawerToggle;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
#Override
public View onCreateView( #NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
#Override
public void onCreate( #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) {
mActionBarDrawerToggle = actionBarDrawerToggle;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true");
}
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
mDrawerLayout.openDrawer(mFragmentContainerView);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#NotNull
public List<NavigationItem> getMenu() {
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("User Profile", getResources().getDrawable(R.drawable.ic_drawer_my_profile), UserFragment.class));
items.add(new NavigationItem("Team Profile", getResources().getDrawable(R.drawable.ic_drawer_my_team), TeamFragment.class));
items.add(new NavigationItem("Explore", getResources().getDrawable(R.drawable.ic_drawer_explore), ExploreFragment.class));
return items;
}
void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
} else {
return;
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState( #NotNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
public void setDrawerLayout(DrawerLayout drawerLayout) {
mDrawerLayout = drawerLayout;
}
public static void saveSharedSetting( #NotNull Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting( #NotNull Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}