So this has been bugging me for like a week and I haven't found the answer yet.
Basically I have this MainActivity which contains the main code and a fragment that work for the listview.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button bNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RoomServer(), "Room Server");
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);
}
}
}
RoomServer.java
public class RoomServer extends ListFragment implements OnItemClickListener{
public RoomServer() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rs, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(getListView().CHOICE_MODE_MULTIPLE);
getListView().setTextFilterEnabled(true);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.rs_list, android.R.layout.simple_list_item_checked);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
Fragment_rs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.RoomServer">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
<Button
android:id="#+id/bNext_rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp"
android:layout_marginBottom="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
The items of listview r declared inside strings.XML
As u can see I'm using CHOICE_MODE_MULTIPLE to create checkbox in the listview. And now I'm stuck at how to get the value of this checkbox. I'm planning to use Volley to send value to my database by a button click. Most of the answer I saw was using the isChecked and stuff but I dont really understand how to implement it in my array adapter.
You can either implement a custom array adapter yourself, or use this method in the ListView class to get a SparseBooleanArray of the indexes of the selected items:
//Submit button example
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get base list
String[] items = getActivity().getResources().getStringArray(R.array.rs_list);
//Get selected items & set intent args
SparseBooleanArray selectedItems = getListView().getCheckedItemPositions();
ArrayList<String> argList = new ArrayList<>();
for (int i = 0; i < selectedItems.size(); i++) {
argList.add(items[selectedItems.keyAt(i)]);
}
//Start activity
Intent intent = new Intent();
intent.putStringArrayListExtra("SelectedItems", argList);
getActivity().startActivity(intent);
}
});
Related
I created an activity with tabs. However, fragments onCreate and onCreateView are not being invoked.
Here is my Fragment class:
public static class PlaceholderFragment extends Fragment {
private int mPage;
private static final String ARG_PAGE = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
Log.d(TAG, "newInstance: run");
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: run");
if (getArguments() != null) {
mPage = getArguments().getInt(ARG_PAGE);
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: run");
View rootView = inflater.inflate(R.layout.fragment_easy, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerView2);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
MyAdapter adapter = new MyAdapter(getContext(), initData(mPage));
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setAdapter(adapter);
return rootView;
}
}
OnCreate method of activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
mSectionsPagerAdapter = new SectionsPagerAdapter(new FragmentActivity().getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById(R.id.viewpager);
mTabLayout = findViewById(R.id.tabs2);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
}
Fragment XML:
<androidx.constraintlayout.widget.ConstraintLayout 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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.stunner.moderstars.ActivityEasy$PlaceholderFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Activity XML:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/easy_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:layout_scrollFlags="scroll|enterAlways|snap"
ads:menu="#menu/menu_activity_pro"
ads:title="#string/app_name">
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:tabMode="scrollable" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="32dp"
android:src="#drawable/ic_sharp_add"
ads:backgroundTint="#color/AccentColor" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Adapter Class:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public 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);
}
#Override
public int getCount() {
return UsefulThings.checkmods(getApplicationContext()).length+1;
}
#Override
public CharSequence getPageTitle(int position) {
return "Mod #"+ (position+1);
}
}
I've read somewhere, that it can be layout problem, but I don't know what to change there.
Solved. The problem was here:
mSectionsPagerAdapter = new SectionsPagerAdapter(new FragmentActivity().getSupportFragmentManager());
I've corrected this to:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
I have created A layout and I dynamically add tabs according to data I receive. I do the same with fragments updating the Text View dynamically. Although when the layout loads and if I swipe through the fragments or view pager (sorry I am new to all these hope my terminology is right) they update just okay (meaning there is sometimes lag in updating not much of an issue) and with right data. although, if in fresh I open the layout and click on tab to change my fragments I get no data or wrong data. Example:- when Layout loads for first time my first & third tab load up fine. If I click on a second Tab (not swiping but touching the tabs on top for the whole time), my second tab doesn't have any data in its fragment. On moving round here and there selecting tabs randomly first tab loads second tabs data, but second tab never loads anything. Its not the same when I swipe if I load page new or for first time.
Let me know where I am doing wrong. Thank you.
Here is my code:-
Layout file - show_score.xml
<android.support.design.widget.CoordinatorLayout
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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.lp.activity.ShowScorePassagesActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/children_school"
android:scaleType="centerCrop"
android:alpha="0.5"
android:layout_below="#+id/appBackBar"/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<include android:id="#+id/appBackBar"
layout="#layout/detail_appbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/passagetabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Fragment File - fragment_show_score_passage.xml
<android.support.constraint.ConstraintLayout 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/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lp.activity.ShowScorePassagesActivity$PlaceholderFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.CardView
android:id="#+id/cardView4"
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardElevation="5dp"
android:scaleType="fitXY"
android:layout_margin="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/scrollbar_shape_style">
<TextView
android:id="#+id/showScore"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="18dp"
android:scaleType="fitXY"
android:text="TextView"
android:autoLink="web"
android:linksClickable="true"
android:padding="20dp"
android:clipToPadding="false"/>
</ScrollView>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="5dp"
android:layout_below="#+id/cardView4"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/scrollbar_shape_style">
<GridView
android:id="#+id/fluencyAudioGrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="2dp"
android:verticalSpacing="5dp"
android:columnWidth="120dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clipToPadding="false"
android:stretchMode="spacingWidthUniform"
layout="#layout/icons_for_dashboard"
android:scrollbarThumbVertical="#drawable/scroolbar_style"
android:scrollbarTrackVertical="#drawable/scroolbar_style_background">
</GridView>
</ScrollView>
</android.support.v7.widget.CardView>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
And the main Java File where the magic happens - ShowScorePassageActivity.java
public class ShowScorePassagesActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public GridView gridView;
public ArrayList<String> gridItems = new ArrayList<String>();
public static TextView fragTextView;
static String fragNewTextView = "";
public static ArrayList<String> fluencyMarksList = new ArrayList<>();
public TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_score_passages);
Intent in = getIntent();
String intentData = in.getStringExtra("intentData");
String fluencyMarks = in.getStringExtra("fluencyMarks");
tabLayout = (TabLayout) findViewById(R.id.passagetabs);
String mFluencyMarkList []= fluencyMarks.split("#");
fluencyMarksList = new ArrayList<String>(Arrays.asList(mFluencyMarkList));
int count = 1;
int counts=fluencyMarksList.size();
for(int i = 0; i < counts; i++){
tabLayout.addTab(tabLayout.newTab().setText("Passage "+count));
count=count+1;
}
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();
}
});
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
int position = tab.getPosition();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
if (position ==0){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0), Html.FROM_HTML_MODE_COMPACT));
}
else if (position ==1){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1) , Html.FROM_HTML_MODE_COMPACT));
}
else if (position ==2){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2) , Html.FROM_HTML_MODE_COMPACT));
}
} else {
if (position ==0){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
}
else if (position ==1){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1)));
}
else if (position ==2){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2)));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
fragTextView.setText("");
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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_show_score_passages, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_show_score_passages, container, false);
fragTextView = (TextView) rootView.findViewById(R.id.showScore);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0) , Html.FROM_HTML_MODE_COMPACT));
} else {
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
Fragment fragment = null;
public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs=NumOfTabs;
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
This is what I did:
It is only a example of what worked for me in the hopes of helping you
In OnCreate:
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
this.addPages(mViewPager);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.mTab_ID);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(listener(mViewPager));
Then add the fragments to the TabLayout by doing:
//ADD ALL PAGES TO TABLAYOUT
private void addPages(ViewPager pager) {
adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new FragmentAdapter1());
adapter.addPage(new FragmentAdapter2());
adapter.addPage(new FragmentAdapter3());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
Then implement TabLayout click events OnTabSelectedListener by doing:
//TabLayout Click Events
private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
i have an Activity with 02 tabLayout
i added First Fragment in my first tab, every thing was just fine since i added my Second Fragment in second tab
my Second Fragment works but when i rotate the device it'll be crash, here is my codes and logCat..
i tried to attach my FragmentTwo to my MainActivity in different ways.. can anybody tell me what's wroNg && how can i do this correctly?
Thanks in advancE.
Main Activity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_note,
R.drawable.ic_tab_calendar
};
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//////// TOOLBAR
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
///////// DRAWER
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView =
(NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener
(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this,
menuItem.getTitle(),
Toast.LENGTH_LONG).show();
return true;
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "ONE");
adapter.addFragment(new FragmentTwo(), "TWO");
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);
return null;
}
}
}
FragmentTwo:
import ir.mirrajabi.persiancalendar.PersianCalendarView;
import ir.mirrajabi.persiancalendar.core.PersianCalendarHandler;
import ir.mirrajabi.persiancalendar.core.interfaces.OnDayClickedListener;
import ir.mirrajabi.persiancalendar.core.interfaces.OnMonthChangedListener;
import ir.mirrajabi.persiancalendar.core.models.CalendarEvent;
import ir.mirrajabi.persiancalendar.core.models.PersianDate;
public class FragmentTwo extends Fragment {
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_two_layout,
container, false);
final PersianCalendarView persianCalendarView = (PersianCalendarView) view.findViewById(R.id.persian_calendar);
final PersianCalendarHandler calendar = persianCalendarView.getCalendar();
final PersianDate today = calendar.getToday();
calendar.addLocalEvent(new CalendarEvent(
today, "Custom event", false
));
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, true), "Custom event 2", true
));
calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
#Override
public void onChanged(PersianDate date) {
Toast.makeText(getActivity(), calendar.getMonthName(date), Toast.LENGTH_SHORT).show();
}
});
persianCalendarView.setOnDayClickedListener(new OnDayClickedListener() {
#Override
public void onClick(PersianDate date) {
for (CalendarEvent e : calendar.getAllEventsForDay(date))
Toast.makeText(getActivity(), e.getTitle(), Toast.LENGTH_LONG).show();
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, false), "Some event that will be added in runtime", false
));
persianCalendarView.update();
}
});
calendar.setHighlightOfficialEvents(false);
TextView txtDayMonth = (TextView) view.findViewById(R.id.txt_day_month);
TextView txtYear = (TextView) view.findViewById(R.id.txt_year);
String dayAndMonth = calendar.getWeekDayName(today) + calendar.formatNumber(today.getDayOfMonth())
+ calendar.getMonthName(today);
txtDayMonth.setText(dayAndMonth);
txtYear.setText(calendar.formatNumber(today.getYear()));
calendar.setColorBackground(getResources().getColor(android.R.color.holo_blue_dark));
persianCalendarView.update();
return view;
}
}
and here is my activity_main.xml :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/base2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"/>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabGravity="fill"
android:theme="#style/ThemeOverlay.AppCompat.Dark"/>
<RelativeLayout
android:id="#+id/relativee"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout_weight="1"/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
and here is fragment_two_layout.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24dp">
<ir.mirrajabi.persiancalendar.PersianCalendarView
android:id="#+id/persian_calendar"
android:layout_width="match_parent"
android:layout_height="290sp"
app:pcv_colorBackground="#292929"
app:pcv_colorDayName="#bab6b6"
app:pcv_colorHoliday="#ffd506"
app:pcv_colorHolidaySelected="#f1f2f3"
app:pcv_colorNormalDaySelected="#d9d9d9"
app:pcv_colorNormalDay="#f3f4f5"
app:pcv_eventUnderlineColor="#02f0f0"
app:pcv_fontSize="20sp"
app:pcv_headersFontSize="14sp"/>
</android.support.v7.widget.CardView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/txt_day_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorAccent"
android:layout_gravity="center_horizontal"
android:textSize="30sp"/>
<TextView
android:id="#+id/txt_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#color/colorAccent"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/change_to_ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change to Gregorian Calendar"
android:textSize="14dp"/>
</LinearLayout>
</LinearLayout>
logCat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.drgnme.listhamrah/com.drgnme.listhamrah.MainActivity}: java.lang.IllegalStateException: Fragment has not been attached yet.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4095)
at android.app.ActivityThread.access$1000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Fragment has not been attached yet.
at android.support.v4.app.Fragment.instantiateChildFragmentManager(Fragment.java:2195)
at android.support.v4.app.Fragment.getChildFragmentManager(Fragment.java:745)
at ir.mirrajabi.persiancalendar.core.fragments.CalendarFragment.createViewPagers(CalendarFragment.java:55)
at ir.mirrajabi.persiancalendar.core.fragments.CalendarFragment.access$000(CalendarFragment.java:27)
at ir.mirrajabi.persiancalendar.core.fragments.CalendarFragment$1.update(CalendarFragment.java:46)
at ir.mirrajabi.persiancalendar.PersianCalendarView.update(PersianCalendarView.java:116)
at com.drgnme.listhamrah.FragmentTwo.onCreateView(FragmentTwo.java:87)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2959)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:550)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1238)
at android.app.Activity.performStart(Activity.java:6340)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2397)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4095)
at android.app.ActivityThread.access$1000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Move all the below code to onActivityCreated():
final PersianCalendarView persianCalendarView = (PersianCalendarView) view.findViewById(R.id.persian_calendar);
final PersianCalendarHandler calendar = persianCalendarView.getCalendar();
final PersianDate today = calendar.getToday();
calendar.addLocalEvent(new CalendarEvent(
today, "Custom event", false
));
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, true), "Custom event 2", true
));
calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
#Override
public void onChanged(PersianDate date) {
Toast.makeText(getActivity(), calendar.getMonthName(date), Toast.LENGTH_SHORT).show();
}
});
persianCalendarView.setOnDayClickedListener(new OnDayClickedListener() {
#Override
public void onClick(PersianDate date) {
for (CalendarEvent e : calendar.getAllEventsForDay(date))
Toast.makeText(getActivity(), e.getTitle(), Toast.LENGTH_LONG).show();
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, false), "Some event that will be added in runtime", false
));
persianCalendarView.update();
}
});
calendar.setHighlightOfficialEvents(false);
TextView txtDayMonth = (TextView) view.findViewById(R.id.txt_day_month);
TextView txtYear = (TextView) view.findViewById(R.id.txt_year);
String dayAndMonth = calendar.getWeekDayName(today) + calendar.formatNumber(today.getDayOfMonth())
+ calendar.getMonthName(today);
txtDayMonth.setText(dayAndMonth);
txtYear.setText(calendar.formatNumber(today.getYear()));
calendar.setColorBackground(getResources().getColor(android.R.color.holo_blue_dark));
persianCalendarView.update();
It is a best practice not do any works other than inflating the layout inside onCreateView()
Just move the persianCalendarView.update() line inside your FragmentTwo's onAttach and remove it from onCreate() :
#Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
persianCalendarView.update();
}
Also remove the update() from the inside of persianCalendarView's OnDayClickedListener. I added that line when I was testing and forgot to remove that from the sample app. You don't have to update persianCalendarView unless you need to change the theme or when adding events in runtime.
Problem is not in your app, Problem is in PersianCalendar Lib,
You are inflating PersianCalendarView in your layout in the Fragment class if you check their implementation in PersianCalendarView.java, 1. they are inflating one layout and they are trying to add one Fragment in that layout in that FragmentManager and its working fine. 2. but not only that in that Fragment they are trying to add ViewPager using getChildFragmentManager() Problem comes her only.
You can ask why? In already one FragmentManager added this Fragment that time its working fine but now it's crashing, For that, you can check the difference between that 2 FragmnetManger in this S0 Answer
For this problem, you can do 3 things,
1. You can create ticket to them and wait for the result
2. You can fix that issue
3. Instead of Adding in Layout, Just Create one ViewGroup in Fragment and when onActivtyCreated called you can Add that layout runtime.
EDITED
I tried that sample, And I tried to add it in Fragment, Problem I faced is, Actually the CalendarView fragment is not attached even though our Fragment attached to the Activity, So as I Mentioned in Solution 3 that we can add it in onActivtyCreated that is wrong.
Then how we can solve temporarily?
I solved by adding the view in onStart(I know this is the wrong place this will call multiple time in the life cycle of Fragment), but we can add some logic and we can add this calendar view only once for making it work now till the dev fix in their lib.
My sample :
My fragment Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ir.mirrajabi.pc.sample.BlankFragment">
<LinearLayout
android:id="#+id/calendar_container"
android:layout_width="match_parent"
android:layout_height="290dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/txt_day_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#f0f2f3"
android:textSize="30sp"/>
<TextView
android:id="#+id/txt_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#c6d9e2"
android:textSize="20sp"/>
</FrameLayout>
Fragment code
public class BlankFragment extends Fragment {
private LinearLayout mLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mLinearLayout= (LinearLayout) view.findViewById(R.id.calendar_container);
return view;
}
#Override
public void onStart() {
super.onStart();
final PersianCalendarView persianCalendarView = new PersianCalendarView(getContext());
// All your remaining PersianCalendarView implementation code here
mLinearLayout.addView(persianCalendarView);
}
}
Note:
If you take above approach, Please add some logic and make sure it's
not adding multiple time when onStart calls in the Fragment.
Check this image sample i have done it Material Design Gridview Image
I have done the same Material Design for grid view Activity on my app, i like to add the onItemClick to new Activity,
I don't know how to do this , please give the brief explanation for the solution
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/appbar_layout"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_android_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="#dimen/expanded_toolbar_title_margin_start"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/code"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:id="#+id/nestedscrollview"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/grid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
res/layout/gridview_custom_layout.xml
<?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"
android:id="#+id/android_gridview_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<com.andexert.library.RippleView
android:id="#+id/more"
rv_centered="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:rv_color="#fff"
app:rv_rippleDuration="200">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:orientation="vertical">
<ImageView
android:id="#+id/gridview_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/gridview_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/grid_image"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Grid View Item"
android:textColor="#444"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
</com.andexert.library.RippleView>
</LinearLayout>
src/MainActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.GridView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
src/CustomAndroidGridViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by HP on 5/11/2016.
*/
public class CustomAndroidGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] string;
private final int[] Imageid;
public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.string = string;
}
#Override
public int getCount() {
return string.length;
}
#Override
public Object getItem(int p) {
return null;
}
#Override
public long getItemId(int p) {
return 0;
}
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
} else {
grid = (View) convertView;
}
return grid;
}
}
PLease give me the solution for call another Actvivty when mouse click on Image (Image 1, Image 2, etc) in Gridview this
Replace your method with mine
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,YourActivity.class);
context.startActivity(intent);
}
});
} else {
grid = (View) convertView;
}
return grid;
}
here is the code to go another activity after click on every image.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(1))){
Intent intent=new Intent(MainActivity.this,SecoundActivity.class);
intent.putExtra("image",gridViewImages[position]);
startActivity(intent);
}
else if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(2))){
Intent intent2=new Intent(MainActivity.this,ThirdActvity.class);
intent2.putExtra("image2",gridViewImages[position]);
startActivity(intent2);
}
//Like this create activites how many images are there in gridViewImages[]array.you have 9 images so create nine activities..you have to send the url in every activity from one activity to another activity according to your requirement
}
});
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
create SecoundActivity.class
public class SecoundActivity extends AppCompactActivity{
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
int position = intent.getExtras().getInt("image");
setContentView(R.layout.secound_view);
image=(ImageView) findViewById(R.id.image);
image.setImageResource(position);
}
}
then Finally create the secound_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_horizontal_margin">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/image"
/>
</LinearLayout>
After 10 seconds in Google...
Starting Another Activity
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);
And Click Listener/Event
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Item Clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
In your MainActivity onCreate method, add an OnItemClick listener for the GridView:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Your Intent goes here
}
});
How can I change the text size of TextView of a fragment. I need it, because text size is small, maybe some users want it to get bigger.
I see, some people advise to use seekbar, or pinch-to-zoom but I can not make it work in a fragment.
Thanks for your help.
my fragment_one.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.aultoon.webovietab.fragments.OneFragment"
android:id="#+id/oneFragmentId"
>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="top|center"
android:gravity="center"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvFragmentOne"
android:text="#string/turkce1"
android:textSize="27sp"
android:textIsSelectable="true"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
</ScrollView>
here is the my OneFragment.java
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
}
here is the my activity
public class SimpleTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "tab1");
adapter.addFragment(new TwoFragment(), "tab2");
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) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.aboutMenuItem:
Intent i = new Intent(this, About_Activity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
First, please read the following Q&A about the textsize "sp" unit in android. You should understand why it used sp as unit for textView and your question should be solved.
Should use "sp" instead of "dp" for text sizes
What is the difference between "px", "dp", "dip" and "sp" on Android?
Android sp vs dp texts - what would adjust the 'scale' and what is the philosophy of support
http://www.singhajit.com/tutorial-1-android-ui-desgin-and-styling/
Now, you should know the usage of "sp" unit in TextView since it can be adjusted due to the user accessibility setting. That's mean if your boss cannot see it clearly, he/she can set the font size setting in the devices instead of code change.
If you still need workaround for the programming. Here is the solution
I have added the seekbar in your fragment layout.
Update xml.
<RelativeLayout android:id="#+id/oneFragmentId"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"/>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:gravity="center"
android:orientation="vertical"
>
<TextView
android:id="#+id/tvFragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:text="Hello world"
android:textIsSelectable="true"
android:textSize="27sp"
/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
I have change your textView text as "Hello world" for testing, please change back to your own string resource.
Here is the fragment code.
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
final TextView tvFragmentOne = (TextView) rootView.findViewById(R.id.tvFragmentOne);
SeekBar lSeekBar = (SeekBar) rootView.findViewById(R.id.seekBar);
lSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvFragmentOne.setTextSize(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return rootView;
}
}
If you like to use other control pinch to zoom, up/down button or other control component to change the text size of the textview, you can do it with the following procedures:
Change other widget instead of seekbar
Change the listener for listening the component control change( like OnSeekBarChangeListener )
Reset the textView size