I'm trying to launch my fragment in the detail fragment & highlight the selected list item (code is there in FragmentWCLine.java) in two pane mode but for some reason it won't do so. Seems to work fine in single pane mode but when it comes to two pane mode it seems to ignore my code in the if(mTwoPane) section within FragmentWCLine.java and then decides to launch an activity rather than showing the fragment in the detail fragment & highlighting the selected list item. In FragmentWCLine.java, I'm not sure what to do with startActivity(new Intent(getActivity(), mWC[position].fragmentClass));. Also FragmentLineChooserList newFragment = new FragmentLineChooserList(); needs to be changed to something else but I have no idea as to what that would be. How can I prevent the mTwoPane code from being ignored so that it does what it is supposed to along with the above that I want to achieve?
WCLineActivity.java
public class WCLineActivity extends ActionBarActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#66CCCC")));
actionBar.setTitle(Html.fromHtml("<font color='#000099'>Hello World</font>"));
if (findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}
FragmentWCLine newFragment = new FragmentWCLine();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.master_container, newFragment);
transaction.commit();
}
}
FragmentWCLine.java
public class FragmentWCLine extends android.support.v4.app.Fragment {
private class WC {
private CharSequence station;
private CharSequence zone;
private Class<? extends Activity> activityClass;
private Class<? extends android.support.v4.app.Fragment> fragmentClass;
public WC(int stationResId, int zoneResId, Class<? extends Activity> activityClass, Class<? extends android.support.v4.app.Fragment> fragmentClass) {
this.fragmentClass = fragmentClass;
this.activityClass = activityClass;
this.station = getResources().getString(stationResId);
this.zone = getResources().getString(zoneResId);
}
#Override
public String toString() { return station.toString(); }
public String getzone(){ return zone.toString(); }
}
private static WC[] mWC;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
public boolean mTwoPane;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_wc_line, container, false);
if (getActivity().findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}else{
mTwoPane = false;
}
// Instantiate the list of stations.
mWC = new WC[]{
new WC(R.string.bank, R.string.zone_1, WCAActivity.class, FragmentWCA.class),
new WC(R.string.wat, R.string.zone_1, WCBActivity.class, FragmentWCB.class)
};
final ListView listView = (ListView)v.findViewById(R.id.list_wc);
listView.setAdapter(new MyAdapter(getActivity(), mWC));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mTwoPane) {
setItemNormal();
View rowView = view;
setItemSelected(rowView);
Fragment newFragment;
switch (position) {
case 0:
newFragment = new FragmentWCA();
break;
case 1:
newFragment = new FragmentWCB();
break;
default:
newFragment = new FragmentWCA();
break;
}
WCLineActivity activity = (WCLineActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getActivity(), WCAActivity.class);
break;
case 1:
intent = new Intent(getActivity(), WCBActivity.class);
break;
default:
intent = new Intent(getActivity(), WCAActivity.class);
break;
}
startActivity(intent);
}
}
public void setItemSelected(View view) {
View rowView = view;
view.setBackgroundColor(Color.parseColor("#66CCCC"));
TextView tv0 = (TextView) rowView.findViewById(R.id.list_item_station);
tv0.setTextColor(Color.parseColor("#000099"));
TextView tv1 = (TextView) rowView.findViewById(R.id.list_item_zone);
tv1.setTextColor(Color.parseColor("#000099"));
}
public void setItemNormal() {
for (int i = 0; i < listView.getChildCount(); i++) {
View v = listView.getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.list_item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.list_item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
return v;
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView station;
TextView zone;
}
LayoutInflater inflater;
WC[] mWC;
public MyAdapter(Context contexts, WC[] samples) {
this.mWC = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mWC.length;
}
#Override
public Object getItem(int position) {
return mWC[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.station = (TextView) convertView.findViewById(R.id.list_item_station);
viewHolder.zone = (TextView) convertView.findViewById(R.id.list_item_zone);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.station.setText(mWC[position].station);
viewHolder.zone.setText(mWC[position].getzone());
return convertView;
}
}
}
FragmentWC.java
public class FragmentWC extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wc, container, false);
return v;
}
}
fragment_wc.xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/detail_container">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Bank"
android:id="#+id/textView0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
fragment_wc_line.xml layout
<?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:id="#+id/fragmentwcline">
<ListView
android:id="#+id/list_wc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="false"
android:layout_centerHorizontal="true"/>
</LinearLayout>
activity_main.xml layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/master_container"
android:name="com.apptacularapps.exitsexpertlondonlite.FragmentMainList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
activity_main.xml layout (sw600dp)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/master_container"/>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:id="#+id/detail_container"/>
</LinearLayout>
My guess is you need to init boolean before fragment transaction:
if (findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}
FragmentWCLine newFragment = new FragmentWCLine();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.master_container, newFragment);
transaction.commit();
Update:
Also update click listener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mTwoPane){
setItemNormal();
View rowView = view;
setItemSelected(rowView);
Fragment newFragment;
switch (position){
case 0:
newFragment = new FragmentWCBank ();
break;
case 1:
newFragment = new FragmentWCWAT();
break;
default:
newFragment = new FragmentWCBank ();
break;
}
WCLineActivity activity = (WCLineActivity) view.getContext();
FragmentTransaction transaction = activity .getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
else{
Intent intent;
switch (position){
case 0:
intent = new Intent(getActivity(), WCBankActivity.class);
break;
case 1:
intent = new Intent(getActivity(), WCWATActivity.class);
break;
default:
intent = new Intent(getActivity(), WCBankActivity.class);
break;
}
startActivity(intent);
}
}
Related
I am using a view pager in my app the view pager contains three layouts and I can swipe between them well and it shows me the different layout files but when I tried to use java orders on this layout I found that nothing changed in the layout for example I tried to change the text of a textView but I found that it hasn't changed
this is the main activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
and this is the java code of the fragment :
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View myView = inflater.inflate(R.layout.fragment_home, container, false);
etAddPost = myView.findViewById(R.id.etAddPost);
TextView tv = myView.findViewById(R.id.testText);
tv.setText("new text");
addPostBtn(myView);
return myView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
and this is the view pager adapter code :
public class SamplePagerAdapter extends PagerAdapter {
Context context;
public SamplePagerAdapter(Context context) {
this.context = context;
}
/**
* #return the number of pages to display
*/
#Override
public int getCount() {
return 3;
}
/**
* #return true if the value returned from {#link #instantiateItem(ViewGroup, int)} is the
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
// BEGIN_INCLUDE (pageradapter_getpagetitle)
/**
* Return the title of the item at {#code position}. This is important as what this method
* <p>
* Here we construct one using the position value, but for real application the title should
* refer to the item's contents.
*/
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "تعلم";
break;
case 1:
title = "الصفحة الرئيسية";
break;
case 2:
title = "التحديات";
break;
}
return title;
}
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at {#code position}. Here we
* inflate a layout from the apps resources and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
// Inflate a new layout from our resources
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert li != null;
View view = null;
switch (position) {
case 0:
view = li.inflate(R.layout.fragment_learn, container, false);
break;
case 1:
view = li.inflate(R.layout.fragment_home, container, false);
break;
case 2:
view = li.inflate(R.layout.fragment_challenges, container, false);
break;
}
// Add the newly created View to the ViewPager
container.addView(view);
// Return the View
return view;
}
/**
* {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
and this is the activity main xml code :
<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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
There are two problems which i am trying to solve.I will accept your answer even if you solve one:
1)My tabLayout does not show the title of the current page.It does not show any text.
2)I use instance of the same fragment across the viewPager.Each fragment fetches some data from net and displays in listView.When i move pages slowly across the viewPager all fragments work properly.But when i move fast or use tabs to reach another page some pages never load.Why would it be?
Activity:
public class WorldNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_world_news);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
FragmentPageAdapter adapter = new FragmentPageAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager,true);
tabLayout.
}
}
Adapter:
public class FragmentPageAdapter extends FragmentStatePagerAdapter {
private String[] tabTitles = new String[]{"Tab1", "Tab2","Tab3" ,"Tab4" ,"Tab5","Tab6","Tab7","Tab8","Tab9","Tab10","Tab11","Tab12","Tab13","Tab14","Tab15"
,"Tab16","Tab17","Tab18","Tab19"};
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Log.d("Adapter","Case 0 called");
return new LisViewFragment2();
case 1:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=al-jazeera-english&sortBy=top&apiKey=6de");
case 2:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=associated-press&sortBy=top&apiKey=6de");
case 3:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=6de");
case 4:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=cnn&sortBy=top&apiKey=6de");
case 5:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=6de");
case 6:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=independent&sortBy=top&apiKey=6de");
case 7:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=metro&sortBy=top&apiKey=6de");
case 8:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=mirror&sortBy=top&apiKey=6de");
case 9:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=newsweek&sortBy=top&apiKey=6de");
case 10:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=new-york-magazine&sortBy=top&apiKey=6de");
case 11:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=reddit-r-all&sortBy=top&apiKey=6de");
case 12:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=reuters&sortBy=top&apiKey=6de");
case 13:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-guardian-uk&sortBy=top&apiKey=6de");
case 14:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-hindu&sortBy=top&apiKey=6de");
case 15:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=67de");
case 16:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-new-york-times&sortBy=top&apiKey=6de");
case 17:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-telegraph&sortBy=top&apiKey=6de");
default:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=usa-today&sortBy=top&apiKey=6de");
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public int getCount() {
return 19;
}
}
Here is the layout:
<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="com.example.android.gametalks.Activity.WorldNews">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:layout_below="#id/sliding_tabs"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
Here is the fragment:
public class ListViewFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<GameNews>> {
public static ListViewFragment newInstance(String url) {
Log.d("ListViewFragment","newInstance created");
ListViewFragment f = new ListViewFragment();
// Supply url input as an argument.
Bundle args = new Bundle();
args.putString("url", url);
f.setArguments(args);
return f;
}
List<GameNews> TotalNews;
ListView gameListView;
LinearLayout emptyView;
Button retryButton;
ListAdapter adapter ;
private View progressBar;
final private int game_loader = 0;
ArrayList<String> urls = new ArrayList<>();
String mUrlString;
int index;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUrlString = getArguments().getString("url");
urls.add(mUrlString);
TotalNews = new ArrayList<GameNews>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
ArrayList<GameNews> gameList = new ArrayList<>();
adapter = new ListAdapter(getActivity(),gameList);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
emptyView = (LinearLayout) view.findViewById(R.id.no_internet_view);
progressBar = view.findViewById(R.id.progress_bar);
retryButton = (Button) view.findViewById(R.id.retry_button);
gameListView = getListView();
emptyView.setVisibility(View.INVISIBLE);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(adapter);
//If connected to net start the loader
if(isConnected())
{
getActivity().getSupportLoaderManager().restartLoader(game_loader, null, ListViewFragment.this);
if(progressBar.getVisibility() == View.VISIBLE)
{
Log.d("Fragment","progress bar is still visible");
}
}
//Otherwise show emptyView and hide listView
else
{
emptyView.setVisibility(View.VISIBLE);
gameListView.setVisibility(View.INVISIBLE);
}
}
#Override
public android.support.v4.content.Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
AdManager manager = new AdManager(getActivity());
return new FragmentLoader(getActivity(),urls,1000);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<List<GameNews>> loader, List<GameNews> games) {
progressBar.setVisibility(View.INVISIBLE);
adapter.clear();
TotalNews.addAll(games);
adapter.addAll(games);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<List<GameNews>> loader) {
adapter.clear();
}
//Method checks if there is internet
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
}
else {
return false;
}
}
}
You are not seeing the title because you have a lot of tabs and there's no place for title. Consider using TabLayout.MODE_SCROLLABLE
tabLayout.setTabMode (TabLayout.MODE_SCROLLABLE);
For First Question
try change tablayout in xml to:
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/red"
android:minHeight="?attr/actionBarSize"
android:elevation="10dp"
app:tabIndicatorColor="#color/black"
app:tabSelectedTextColor="#color/black"
app:tabTextColor="#color/white"
app:tabGravity="fill"
/>
choose your favorits colors
I'm trying to get the selected item within my list view to stay highlighted when I select it but for some reason it won't do that the moment the selected item is not in view. E.g. When I select Item 4, that list item does get highlighted but when I scroll through the list it doesn't stay highlighted and then other items randomly become highlighted. Even when I return to Item 4, that item is no longer highlighted. I really don't understand why this is happening. What can be done to resolve this issue? All relevant help would be appreciated.
fragment_main.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:id="#+id/fragmentmain">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="false"
android:layout_centerHorizontal="true"
android:choiceMode="singleChoice"/>
</LinearLayout>
MainListAdapter.java
public class MainListAdapter extends BaseAdapter implements Filterable {
private List<Main> mData;
private List<Main> mFilteredData;
private LayoutInflater mInflater;
private ItemFilter mFilter;
public MainListAdapter (List<Main> data, Context context) {
mData = data;
mFilteredData = new ArrayList(mData);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mFilteredData.size();
}
#Override
public Main getItem(int position) {
return mFilteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item);
holder.description = (TextView) convertView.findViewById(R.id.item_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Main main = getItem(position);
holder.title.setText(main.getContinent());
holder.description.setText(main.getDescription());
if (main.isSelected()) {
convertView.setBackgroundColor(Color.parseColor("#1C3F96"));
holder.title.setTextColor(Color.parseColor("#FFFFFF"));
holder.description.setTextColor(Color.parseColor("#FFFFFF"));
} else {
convertView.setBackgroundColor(Color.TRANSPARENT);
holder.title.setTextColor(Color.parseColor("#FFFFFF"));
holder.description.setTextColor(Color.parseColor("#B5B5B5"));
}
holder.title.setText(mFilteredData.get(position).getContinent());
holder.description.setText(mFilteredData.get(position).getDescription());
return convertView;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
/**
* View holder
*/
static class ViewHolder {
private TextView title;
private TextView description;
}
/**
* Filter for filtering list items
*/
/**
* <p>An array filter constrains the content of the array adapter with
* a prefix. Each item that does not start with the supplied prefix
* is removed from the list.</p>
*/
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (TextUtils.isEmpty(constraint)) {
results.count = mData.size();
results.values = new ArrayList(mData);
} else {
//Create a new list to filter on
List<Main> resultList = new ArrayList<Main>();
for (Main str : mData) {
if (str.getContinent().toLowerCase().contains(constraint.toString().toLowerCase())) {
resultList.add(str);
}
}
results.count = resultList.size();
results.values = resultList;
}
return results;
}
/**
* Runs on ui thread
* #param constraint the constraint used for the result
* #param results the results to display
*/
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
mFilteredData.clear();
notifyDataSetInvalidated();
} else {
mFilteredData = (ArrayList<Main>)results.values;
notifyDataSetChanged();
}
}
}
}
Main.java (in the "data" package)
public class Main {
public Main(){}
private String continent;
private String description;
private boolean selected;
public String getContinent(){
return continent;
}
public void setContinent(String continent){
this.continent = continent;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
private int _id;
public void getID(int _id){
this._id = _id;
}
public int setID(){
return _id;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity {
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentMain newFragment = new FragmentMain();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.master_container, newFragment);
transaction.commit();
if (findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
}
FragmentMain.java
public class FragmentMain extends ListFragment implements SearchView.OnQueryTextListener {
private MainListAdapter mAdapter;
public FragmentMain() {
// Required empty constructor
}
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
public boolean mTwoPane;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
//Tell the system to call onCreateOptionsMenu
setHasOptionsMenu(true);
initialize(view);
return view;
}
List<Main> list = new ArrayList<>();
private void initialize(View view) {
String[] items = getActivity().getResources().getStringArray(R.array.items);
String[] itemDescriptions = getActivity().getResources().getStringArray(R.array.item_descriptions);
for (int n = 0; n < items.length; n++){
Main world = new Main();
world.setID();
world.setContinent(items[n]);
world.setDescription(itemDescriptions[n]);
list.add(world);
}
mAdapter = new MainListAdapter(list, getActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View v = getView();
mTwoPane = getActivity().findViewById(R.id.detail_container) != null;
ListView lv = (ListView)v.findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the adapter, then get the name from the adapter at that position
MainListAdapter adapter = (MainListAdapter) parent.getAdapter();
Main main = adapter.getItem(position);
if (mTwoPane) {
setItemNormal();
View rowView = view;
setItemSelected(rowView);
Fragment newFragment;
switch (position) {
case 0:
newFragment = new Fragment0();
break;
case 1:
newFragment = new Fragment1();
break;
case 2:
newFragment = new Fragment2();
break;
case 3:
newFragment = new Fragment3();
break;
case 4:
newFragment = new Fragment4();
break;
case 5:
newFragment = new Fragment5();
break;
case 6:
newFragment = new Fragment6();
break;
case 7:
newFragment = new Fragment7();
break;
case 8:
newFragment = new Fragment8();
break;
case 9:
newFragment = new Fragment9();
break;
case 10:
newFragment = new Fragment10();
break;
case 11:
newFragment = new Fragment11();
break;
case 12:
newFragment = new Fragment12();
break;
case 13:
newFragment = new Fragment13();
break;
case 14:
newFragment = new Fragment14();
break;
case 15:
newFragment = new Fragment15();
break;
case 16:
newFragment = new Fragment16();
break;
case 17:
newFragment = new Fragment17();
break;
case 18:
newFragment = new Fragment18();
break;
case 19:
newFragment = new Fragment19();
break;
case 20:
newFragment = new Fragment20();
break;
default:
newFragment = new Fragment0();
}
MainActivity activity = (MainActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fade_out, R.anim.fade_in);
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (main.equals(view.getResources().getString(R.string.item0))) {
intent = new Intent(getActivity(), Activity0.class);
} else if (main.equals(view.getResources().getString(R.string.item1))) {
intent = new Intent(getActivity(), Activity1.class);
} else if (main.equals(view.getResources().getString(R.string.item2))) {
intent = new Intent(getActivity(), Activity2.class);
} else if (main.equals(view.getResources().getString(R.string.item3))) {
intent = new Intent(getActivity(), Activity3.class);
} else if (main.equals(view.getResources().getString(R.string.item4))) {
intent = new Intent(getActivity(), Activity4.class);
} else if (main.equals(view.getResources().getString(R.string.item5))) {
intent = new Intent(getActivity(), Activity5.class);
} else if (main.equals(view.getResources().getString(R.string.item6))) {
intent = new Intent(getActivity(), Activity6.class);
} else if (main.equals(view.getResources().getString(R.string.item7))) {
intent = new Intent(getActivity(), Activity7.class);
} else if (main.equals(view.getResources().getString(R.string.item8))) {
intent = new Intent(getActivity(), Activity8.class);
} else if (main.equals(view.getResources().getString(R.string.item9))) {
intent = new Intent(getActivity(), Activity9.class);
} else if (main.equals(view.getResources().getString(R.string.item10))) {
intent = new Intent(getActivity(), Activity10.class);
} else if (main.equals(view.getResources().getString(R.string.item11))) {
intent = new Intent(getActivity(), Activity11.class);
} else if (main.equals(view.getResources().getString(R.string.item12))) {
intent = new Intent(getActivity(), Activity12.class);
} else if (main.equals(view.getResources().getString(R.string.item13))) {
intent = new Intent(getActivity(), Activity13.class);
} else if (main.equals(view.getResources().getString(R.string.item14))) {
intent = new Intent(getActivity(), Activity14.class);
} else if (main.equals(view.getResources().getString(R.string.item15))) {
intent = new Intent(getActivity(), Activity15.class);
} else if (main.equals(view.getResources().getString(R.string.item16))) {
intent = new Intent(getActivity(), Activity16.class);
} else if (main.equals(view.getResources().getString(R.string.item17))) {
intent = new Intent(getActivity(), Activity17.class);
} else if (main.equals(view.getResources().getString(R.string.item18))) {
intent = new Intent(getActivity(), Activity18.class);
} else if (main.equals(view.getResources().getString(R.string.item19))) {
intent = new Intent(getActivity(), Activity19.class);
} else if (main.equals(view.getResources().getString(R.string.item20))) {
intent = new Intent(getActivity(), Activity20.class);
} else {
intent = new Intent(getActivity(), Activity0.class);
}
startActivity(intent);
}
}
public void setItemSelected(View view) {
View rowView = view;
view.setBackgroundColor(Color.parseColor("#1C3F96"));
TextView tv0 = (TextView) rowView.findViewById(R.id.item);
tv0.setTextColor(Color.parseColor("#FFFFFF"));
TextView tv1 = (TextView) rowView.findViewById(R.id.item_description);
tv1.setTextColor(Color.parseColor("#FFFFFF"));
}
public void setItemNormal() {
for (int i = 0; i < getListView().getChildCount(); i++) {
View v = getListView().getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.item));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.item_description));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem searchViewMenuItem = menu.findItem(R.id.action_search);
SearchView mSearchView = (SearchView) MenuItemCompat.getActionView(searchViewMenuItem);
int searchImgId0 = android.support.v7.appcompat.R.id.search_button;
ImageView v0 = (ImageView) mSearchView.findViewById(searchImgId0);
v0.setImageResource(R.drawable.ic_action_search_light);
int searchImgId1 = android.support.v7.appcompat.R.id.search_close_btn;
ImageView v1 = (ImageView) mSearchView.findViewById(searchImgId1);
v1.setImageResource(R.drawable.ic_action_content_clear_light);
super.onPrepareOptionsMenu(menu);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Set up search view
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setIconifiedByDefault(true);
searchView.clearAnimation();
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String newText) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return false;
}
}
list_item.xml
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:baselineAligned="false"
android:paddingStart="12dp"
android:paddingEnd="12dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:textColor="?android:attr/textColorPrimary" />
<TextView android:id="#+id/item_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/item"
android:layout_alignStart="#id/item"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary" />
</RelativeLayout>
Updated screenshot 31/07/2015
Android ListView reuses its views while you scroll it. You need to store information about a selected item in an item object and check if it is selected inside getView.
Call setItemSelected if it is selected and setItemNormal otherwise. This way you will update the selected state of each item while you scrolling the list.
EDIT
#Override
public Main getItem(int position) {
return mFilteredData.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.item);
holder.description = (TextView) convertView.findViewById(R.id.item_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Main main = getItem(position);
holder.title.setText(main.getContinent());
holder.description.setText(main.getDescription());
if (main.isSelected()) {
convertView.setBackgroundColor(Color.parseColor("#1C3F96"));
holder.title.setTextColor(Color.parseColor("#FFFFFF"));
holder.description.setTextColor(Color.parseColor("#FFFFFF"));
} else {
convertView.setBackgroundColor(Color.TRANSPARENT);
holder.title.setTextColor(Color.parseColor("#FFFFFF"));
holder.description.setTextColor(Color.parseColor("#B5B5B5"));
}
return convertView;
}
Inside your onItemClick:
...
switch (position) {
case 0:
newFragment = new Fragment0();
break;
case 1:
newFragment = new Fragment1();
break;
// etc..
default:
newFragment = new Fragment0();
}
I have a MainActivity which is a ActionBarActivity with viewPager inside.
Then I have 3 pages.
In the first page there is a tableLayout with tableRow clickListener (inside blocks) from where I would like to start an intent to another layout without hiding TabBar. Here is my code:
MainActivity.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
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 FirstFragment (defined as a static inner class below).
//return FirstFragment.newInstance(position + 1);
switch(position) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class FirstFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
//private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.first_fragment, container, false);
createTable(rootView);
return rootView;
}
public static FirstFragment newInstance(String string) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString("msg", "PROVA 1");
fragment.setArguments(args);
return fragment;
}
void createTable(View rootView){
TableLayout ll = (TableLayout) rootView
.findViewById(R.id.tableLayout);
String categorie[];
// MyDatabase db=new MyDatabase(getActivity().getApplicationContext());
// db.open(); //apriamo il db
MyDatabase db = new MyDatabase(getActivity().getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
db.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c=db.fetchCategorie(); // query
//startManagingCursor(c);
//qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview
int categoriaColumn=c.getColumnIndex(MyDatabase.CategorieMetaData.PRODUCT_CATEGORIA_KEY); //indici delle colonne
//int priceCol=c.getColumnIndex(MyDatabase.ProductsMetaData.PRODUCT_PRICE_KEY);
ArrayList<String> categorieList = new ArrayList<String>();
if(c.moveToFirst()){ //se va alla prima entry, il cursore non è vuoto
do {
categorieList.add(c.getString(categoriaColumn)); //add to arraylist
//productsTv.append("Product Name:"+c.getString(nameCol)+", Price:"+c.getInt(priceCol)+"\n"); //estrazione dei dati dalla entry del cursor
//Log.d("Prova", "PROVA:"+ "Product Name:"+c.getString(categoriaColumn)+", Price:"+c.getInt(priceCol)+"\n");
} while (c.moveToNext());//iteriamo al prossimo elemento
}
db.close();
categorie = categorieList.toArray(new String[categorieList.size()]);
for (int i = 0; i < categorie.length; i++) {
TableRow tbRow = new TableRow(getActivity().getApplicationContext());
tbRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView tv1 = new TextView(getActivity().getApplicationContext());
tv1.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
tbRow.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
ImageView imageView = new ImageView(getActivity().getApplicationContext());
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
tv1.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv1.setId(i);
tv1.setText(categorie[i]);
tv1.setTextColor(Color.parseColor("#000000"));
tbRow.addView(imageView);
tbRow.addView(tv1);
ll.addView(tbRow, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
final String finalCategorie[] = categorie;
final int finalI = i;
final View finalRootView = rootView;
tbRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Intent newIntent = new Intent(MainActivity.this, detailActivity.class);
// newIntent.putExtra("key", strings[finalI]);
Log.d("TEST", "Row selected: " + finalCategorie[finalI]);
// startActivity(newIntent);
// Intent intent = new Intent(getActivity(), EventiFragment.class);
// startActivity(intent);
}
});
}
}
}
public static class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String string) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
public static class ThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentThird);
tv.setText(getArguments().getString("msg"));
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 3");
f.setArguments(b);
return f;
}
}
public static class EventiFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.eventi_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentEventi);
tv.setText(getArguments().getString("msg"));
return v;
}
public static EventiFragment newInstance(String string) {
EventiFragment f = new EventiFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
}
first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="#string/main_photo_description"
android:scaleType="centerCrop"
android:src="#drawable/main_photo" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TableLayout>
</LinearLayout>
</ScrollView>
eventi_fragment.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/FragmentEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textSize="26sp"/>
So I would create a separate layout, but instead of putting the layout in two separate XML files, put it all in one. For example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/intent_replacement"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Here's the stuff for the supposed intent -->
</RelativeLayout>
</RelativeLayout>
So in this you can have one attribute called visible then programmatically you just get the Layout as an object and when an item in the table is clicked on use intentLayoutObject.setVisibility(true)
Likewise when you get back button pressed intentLayoutObject.setVisibility(false)
I dont understand why when I click in item of the drawerlist, the drawer just close and doesnt do anything. I think the DrawerItemClickListener it's not working correctly... Could you help me? I'm new in java.
my onCreate:
setContentView(R.layout.meus_horarios);
setTitle(" Meus Horários");
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_discard, "Brinquedos");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_discard, "Meus Horários");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_discard, "Sair");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
and my classes:
public class DrawerItemCustomAdapter extends ArrayAdapter<ObjectDrawerItem> {
Context mContext;
int layoutResourceId;
ObjectDrawerItem data[] = null;
public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, ObjectDrawerItem[] data) {
super(mContext, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItem = convertView;
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
listItem = inflater.inflate(layoutResourceId, parent, false);
ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon);
TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName);
ObjectDrawerItem folder = data[position];
imageViewIcon.setImageResource(folder.icon);
textViewName.setText(folder.name);
return listItem;
}
public class ObjectDrawerItem {
public int icon;
public String name;
// Constructor.
public ObjectDrawerItem(int icon, String name) {
this.icon = icon;
this.name = name;
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
CarregarTelaBrinquedos();
break;
case 1:
CarregarMeusHorarios();
break;
case 2:
btnSair.callOnClick();
break;
default:
break;
}
}
the fragment :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Navigation Drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
/>
<!-- Conteudo principal -->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MeusHorarios"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fundoo" >
<ListView
android:id="#+id/lstMeusHorarios"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Try the following:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
mDrawerLayout.closeDrawer(mDrawerList);
Handler handler0 = new Handler();
handler0.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 250);
break;
case 1:
mDrawerLayout.closeDrawer(mDrawerList);
Handler handler0 = new Handler();
handler0.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
}, 250);
break;
//case 2: etc...
}
}
}