Using Android's Studio I started with a Navigation Drawer activity. Then I added a Master Detail activity making a "real" class from the DummyContent class template. The application works when hard coding the items. My needs are to use multiple languages so I must use strings.xml for the language translations.
I extended ProductsAZ.java using Activity trying unsuccessfully to use "this" and "getString()". I can assign String header1 = getString(R.string.header1);. How do I use this design/class to call strings from strings.xml when adding a new Product item?
addItem(new Product("1", "1_Title_here", "1_Header_here", "1_Body_here"));
addItem(new Product("2", "2_Title_here", "2_Header_here", "2_Body_here"));
addItem(new Product("3", "3_Title_here", "3_Header_here", "3_Body_here"));
Desire is:
addItem(new Product("1", "#string/1_Title_here", "#string/1_Header_here", "#string/1_Body_here"));
ProductAZ.java
import android.app.Activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProductAZ extends Activity {
// An array of items.
// public static List<Product> ITEMS = new ArrayList<>();
public static List<Product> ITEMS = new ArrayList<>();
// A map of items, by ID.
public static Map<String, Product> ITEM_MAP = new HashMap<>();
// Add items.
static {
addItem(new Product("1", "1_Title_here", "1_Header_here", "1_Body_here"));
addItem(new Product("2", "2_Title_here", "2_Header_here", "2_Body_here"));
addItem(new Product("3", "3_Title_here", "3_Header_here", "3_Body_here"));
}
private static void addItem(Product product) {
ITEMS.add(product);
ITEM_MAP.put(product.id, product);
}
// An item representing a piece of content.
public static class Product {
public final String id;
public final String title;
public final String header;
public final String details;
public Product(String id, String title, String header, String details) {
this.id = id;
this.title = title;
this.header = header;
this.details = details;
}
#Override
public String toString() {
return title;
}
}
}
ProductListActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import java.util.List;
/**
* An activity representing a list of Products. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link ProductDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class ProductListActivity extends AppCompatActivity {
/**
* 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_product_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
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();
}
});
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
View recyclerView = findViewById(R.id.product_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.product_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(ProductAZ.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<ProductAZ.Product> mValues;
public SimpleItemRecyclerViewAdapter(List<ProductAZ.Product> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).title);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ProductDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ProductDetailFragment fragment = new ProductDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.product_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra(ProductDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public ProductAZ.Product mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
ProductDetailFragment.java
import android.app.Activity;
import android.support.design.widget.CollapsingToolbarLayout;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A fragment representing a single Product detail screen.
* This fragment is either contained in a {#link ProductListActivity}
* in two-pane mode (on tablets) or a {#link ProductDetailActivity}
* on handsets.
*/
public class ProductDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "item_id";
// The content this fragment is presenting.
// private ProductAZ.Product mItem;
private ProductAZ.Product mProduct;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ProductDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mProduct = ProductAZ.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
Activity activity = this.getActivity();
CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(mProduct.title);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_detail, container, false);
// Show the content as text in a TextView.
if (mProduct != null) {
((TextView) rootView.findViewById(R.id.product_detail)).setText(mProduct.details);
}
return rootView;
}
}
ProductDetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
/**
* An activity representing a single Product detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link ProductListActivity}.
*/
public class ProductDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own detail action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ProductDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ProductDetailFragment.ARG_ITEM_ID));
ProductDetailFragment fragment = new ProductDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.product_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this, ProductListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
product_detail.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/product_detail"
style="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textIsSelectable="true"
tools:context="com.bobh.znd6.ProductDetailFragment"/>
product_list.xml (small display)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView 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/product_list"
android:name="com.bobh.znd5.ProductListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context="com.bobh.znd6.ProductListActivity"
tools:listitem="#layout/product_list_content"/>
product_list_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"/>
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"/>
</LinearLayout>
Solved. I found the solution in link. I needed to delete my switch statement in ProductAZ.java. Then in DetailListActivity.java I edited the onCreate method. Using the prior post's outline fitting my class/method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DummyContent.ITEMS.isEmpty())
{
DummyContent.addItem(new DummyItem("1", getResources().getString(R.string.menu1)));
DummyContent.addItem(new DummyItem("2", getResources().getString(R.string.menu2)));
DummyContent.addItem(new DummyItem("3", getResources().getString(R.string.menu3)));
}
Related
I have implemented two pie charts in two different fragments. Whenever I click on a pie chart it will call the second fragments click events on both fragments.
Here is my MainActivity.java code.
package longitude.com.anychart;
import android.content.res.Resources;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.dataentry.ValueDataEntry;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
/**
* 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}.
*/
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private AccountDashboardAdapter mSectionsPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mViewPager = (ViewPager) findViewById(R.id.container);
//mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ArrayList<DataEntry> dateData = new ArrayList<>();
dateData.add(new ValueDataEntry("Apples", 123456));
dateData.add(new ValueDataEntry("Pears", 852465));
dateData.add(new ValueDataEntry("Bananas", 753159));
dateData.add(new ValueDataEntry("Grapes", 963215));
dateData.add(new ValueDataEntry("Oranges", 415263));
ArrayList<DataEntry> collectorData = new ArrayList<>();
collectorData.add(new ValueDataEntry("Applessssss", 6371664));
collectorData.add(new ValueDataEntry("Pearsssss", 789622));
collectorData.add(new ValueDataEntry("Bananasssss", 7216301));
collectorData.add(new ValueDataEntry("Grapesssss", 1486621));
collectorData.add(new ValueDataEntry("Orangesssss", 1200000));
HashMap<String, ArrayList<DataEntry>> childData=new LinkedHashMap<>();
childData.put("Apples",collectorData);
childData.put("Pears",collectorData);
childData.put("Bananas",collectorData);
childData.put("Grapes",collectorData);
childData.put("Oranges",collectorData);
childData.put("Applessssss",dateData);
childData.put("Pearsssss",dateData);
childData.put("Bananasssss",dateData);
childData.put("Grapesssss",dateData);
childData.put("Orangesssss",dateData);
mSectionsPagerAdapter = new AccountDashboardAdapter(getResources(), getSupportFragmentManager(), dateData, collectorData, childData);
mViewPager.setOffscreenPageLimit(5);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
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();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class AccountDashboardAdapter extends FragmentStatePagerAdapter {
private final List<DataEntry> collectorData;
private final HashMap<String, ArrayList<DataEntry>> childData;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
List<DataEntry> dateData;
/**
* Create pager adapter
*
* #param resources
* #param fm
* #param data
* #param childData
*/
public AccountDashboardAdapter(final Resources resources, FragmentManager fm, List<DataEntry> data, List<DataEntry> collectorData, HashMap<String, ArrayList<DataEntry>> childData) {
super(fm);
this.dateData = data;
this.collectorData = collectorData;
this.childData = childData;
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
// First Fragment of First Tab
//result = new DatewiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle = new Bundle();
bundle.putSerializable("data", (Serializable) dateData);
bundle.putSerializable("childData", childData);
result.setArguments(bundle);
break;
case 1:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment2();
Bundle bundle1 = new Bundle();
bundle1.putSerializable("data", (Serializable) collectorData);
bundle1.putSerializable("childData", childData);
result.setArguments(bundle1);
break;
case 2:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle2 = new Bundle();
bundle2.putSerializable("data", (Serializable) dateData);
bundle2.putSerializable("childData", childData);
result.setArguments(bundle2);
break;
default:
result = null;
break;
}
return result;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(final int position) {
switch (position) {
case 0:
return "DATEWISE";
case 1:
return "COLLECTORWISE";
default:
return null;
}
}
/**
* On each Fragment instantiation we are saving the reference of that Fragment in a Map
* It will help us to retrieve the Fragment by position
*
* #param container
* #param position
* #return
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
/**
* Remove the saved reference from our Map on the Fragment destroy
*
* #param container
* #param position
* #param object
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
/**
* Get the Fragment by position
*
* #param position tab position of the fragment
* #return
*/
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
My First Fragment1.java code
package longitude.com.anychart;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment1 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("1st Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment1==>" + event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
My Second Fragment2.java code
package longitude.com.anychart;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment2 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("2nd Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment2==>"+event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
fragment1.xml
<?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">
<Button
android:id="#+id/btn_back"
android:enabled="false"
android:layout_width="60dp"
android:layout_height="40dp"
android:text="BACK" />
<com.anychart.AnyChartView
android:id="#+id/any_chart_view1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Here is my code link: https://drive.google.com/file/d/1YnIL1fE52W_Gy4yuc2rYb4fh4Y1hGNuG/view?usp=sharing
Unfortunately, now we have no idea what exactly happens with event dispatching in Fragments. But I would like to bring to your attention that there's a possible workaround.
Click on a chart returns correct point name and value. Only the fragment name is wrong. The name is hardcoded in the click event handler.
So if the fragment name is not required in output, you can just drop it. If the name is required you can apply a specific ID to the Fragment and then get that ID from active fragment view. This should solve the issue as a temporary workaround.
I've successfully implemented cardview and recycleview in my navigation drawer. Now the problem is, when ever I clicked in my first cardview which will take me to my first fragment and then press back, my cardviews aren't in my list tab(1st fragment) anymore. The only option view the list of cardviews is to swipe to my navigation drawer again and click on the first fragment to view the cardviews.
here's my code for the
RecyclerViewAdapter.class
package com.example.guitarista.citem.Exhibitor;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.guitarista.citem.Gallery_SpringForward.GalleryFragment;
import com.example.guitarista.citem.Gallery_activity.GalleryActivity;
import com.example.guitarista.citem.R;
import java.util.List;
/**
* Created by smdojt on 1/24/2017.
*/
public class TabInt_RV_Adapter extends RecyclerView.Adapter<TabInt_RV_Adapter.ItemViewHolder> {
public static class ItemViewHolder extends RecyclerView.ViewHolder {
static CardView cv;
TextView itemName;
TextView itemCathegory;
ImageView itemPhoto;
ItemViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
itemName = (TextView) itemView.findViewById(R.id.item_name);
itemCathegory = (TextView) itemView.findViewById(R.id.item_cathegory);
itemPhoto = (ImageView) itemView.findViewById(R.id.item_photo);
}
}
List<Exhibitors_Int> items;
Context context;
TabInt_RV_Adapter(List<Exhibitors_Int> items, Context context) {
this.context = context;
this.items = items;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_exhibitor_tabint_item, viewGroup, false);
ItemViewHolder ivh = new ItemViewHolder(v);
return ivh;
}
#Override
public void onBindViewHolder(ItemViewHolder itemViewHolder, final int i) {
itemViewHolder.cv.setOnClickListener(null);
itemViewHolder.itemName.setText(items.get(i).name);
itemViewHolder.itemCathegory.setText(items.get(i).cathegory);
itemViewHolder.itemPhoto.setImageResource(items.get(i).photoId);
ItemViewHolder.cv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 1) {
//Toast.makeText(context, "Index position is 1", Toast.LENGTH_SHORT).show();
Intent intent = new Intent (context, GalleryActivity.class);
context.startActivity(intent);
}
else if (i == 2) {
//Toast.makeText(context, "Index position is 2 ", Toast.LENGTH_SHORT).show();
AppCompatActivity activity = (AppCompatActivity) v.getContext();
GalleryFragment gf = new GalleryFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, gf).addToBackStack(null).commit();
}
}
});
}
#Override
public int getItemCount() {
return items.size();
}
}
notice that on my onClick, there's two versions of gallery. The first one is the original activity, and the second one is implemented for fragment.
So when I clicked on the first one, and then back pressed, the cardviews will show. Now whats the problem with this? I cant swipe through navigation drawer when I click the activity version of gallery.
Where in, when I clicked on the second cardview which is fragment implemented, the navigation drawer swipe does work while inside the gallery, but when I press back, the lists of cardviews wont show.
even when I put these lines of code for fragment:
GalleryFragment fr = new GalleryFragment();
Bundle args = new Bundle();
fr.setArguments(args);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I'll just even get an error for getFragmentManager();
Is there any other way to solve this?
CODE FOR CARDVIEWS
package com.example.guitarista.citem.Exhibitor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.guitarista.citem.R;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class TabInternationalFragment extends Fragment {
private List<Exhibitors_Int> items;
private RecyclerView rv;
public TabInternationalFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_exhibitor_tab_international, container, false);
rv=(RecyclerView)v.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
//GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
//rv.setLayoutManager(glm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
return v;
}
private void initializeData() {
items = new ArrayList<>();
items.add(new Exhibitors_Int("A. GARCIA CRAFTS", "FURNITURE", R.drawable.image1));
items.add(new Exhibitors_Int("BALEX BOXES", "HOLIDAY DECORATION", R.drawable.image2));
items.add(new Exhibitors_Int("CAGAYAN DE ORO HANDMADE PAPER", "HOME DECOR/HOUSEWARE", R.drawable.image3));
}
private void initializeAdapter(){
TabInt_RV_Adapter adapter = new TabInt_RV_Adapter(items, getContext());
rv.setAdapter(adapter);
}
}
If you want to keep your first activity as it was after you've pressed the back button, you should define the launch mode of your first activity in the AndroidManifest.xml. Also define the parent activity for your second activity, so Android knows which activity it should navigate back to when you press the back button.
<activity
android:name=".activity.HomeActivity"
android:label="#string/app_name"
android:launchMode="singleTop" />
<activity
android:name=".activity.GalleryActivity"
android:label="#string/app_name"
android:parentActivityName=".activity.HomeActivity"
tools:ignore="UnusedAttribute">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activity.HomeActivity" />
</activity>
The singleTop launch mode will make sure that no new instance of that activity will be created if there is already an instance in the activity stack. So your cards will still be visible in your first activity after pressing the back button.
This question already has answers here:
Send data from activity to fragment in Android
(22 answers)
Closed 7 years ago.
It may be dumb question but am struggling with this how to pass value between activity and viewpager. Now let me explain my requirement i have two tabs namely task and calls . Having one button in task when user press that it will go to new activity from there will be two forms one is edittext and spinner need to populate listview in task fragment from that activity data so far what i have tried is:
This is my Main activity:
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Bundle bundle=getIntent().getExtras();
// Intent intent=getIntent();
// ActivityView activityView=(ActivityView)intent.getSerializableExtra("yog");
// intent.putExtra("yogs",activityView);
// Bundle bundle=new Bundle();
// bundle.putSerializable("yogs",activityView);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String yogan = bundle.getString("yog");
String yogans = bundle.getString("yogs");
Bundle bundle1 = new Bundle();
bundle.putString("yoges", yogan);
bundle.putString("yogesh", yogans);
Task task = new Task();
task.setArguments(bundle1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
/**
* 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 PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
Task task=new Task();
return task;
case 1:
Calls calls=new Calls();
return calls;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Task";
case 1:
return "Call";
}
return null;
}
}
}
This is my task fragment(where listview is gets populated)
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class Task extends Fragment
{
List<ActivityView>activityViews;
ActivityView activityView=new ActivityView();
ActivityListAdapter activityListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview= inflater.inflate(R.layout.yog,container,false);
ListView listview=(ListView)rootview.findViewById(R.id.listView);
if (activityViews == null)
{
activityViews = new ArrayList<ActivityView>();
}
if(getArguments()!=null) {
getArguments().getSerializable("yog");
}
activityViews.add(activityView);
activityListAdapter = new ActivityListAdapter(getActivity(), R.id.listView, activityViews);
listview.setAdapter(activityListAdapter);
activityListAdapter.notifyDataSetChanged();
Button btn=(Button)rootview.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), DetailActivity.class);
startActivity(intent);
}
});
return rootview;
}
}
This is the activity where data go to populate listview in task fragment:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class DetailActivity extends AppCompatActivity {
ActivityView activityView = new ActivityView();
// public static String endpoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText editText = (EditText) findViewById(R.id.editText);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.yog, R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
final Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityView.setDescription(editText.getText().toString());
activityView.setStatus(spinner.getSelectedItem().toString());
// Bundle bundle=new Bundle();
// bundle.putSerializable("yog", activityView);
Task task=new Task();
//task.setArguments(bundle);
android.support.v4.app. FragmentManager fm=getSupportFragmentManager();
android.support.v4.app. FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.container,task,"");
ft.commit();
}
});
}
}
Here how to pass data between activity and fragment of viewpager can anybody help me out? Thanks in advance!
You can use a Bundle to pass datas from an Activity to a Fragment:
In the Activity, create your Bundle and add it to the Fragment
Bundle myBundle = new Bundle();
myBundle .putLong( "exampleId", mExampleId);
myBundle .putString("exampleName", mName);
...
myFragment.setArguments( myBundle );
Then, when the Fragment is created, get the values in your Bundle using the function getArguments() like:
Long exampleId = getArguments().getLong("exampleId");
And even set a default value if you don't find the key in your Bundle
String exampleName = getArguments().getString( "exampleName", "None"));
You should create a NewInstance method inside your fragment. In short, it could look like this:
public class MyFragment {
private int value;
private static final String ARG_VALUE = "argValue";
public static MyFragment NewInstance(int value) {
Bundle args = new Bundle();
args.putInt(ARG_VALUE, value);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate() {
Bundle args = getArguments();
this.value = args.getInt(ARG_VALUE, 0); // Default 0 if key not found.
}
}
And you just pass in that value anytime you create the fragment:
MyFragment tenFragment = MyFragment.newInstance(10);
Then it can be used in a fragment transaction or inserted into a FragmentStatePagerAdapter however you need it. The same principle applies to any data type, so you can do this if you need to pass in Strings, or your own serializable object, etc.
I'm working on an app that allows the user to add an item to a list (todo list). The user has the choise of which list the item will go into. The app uses Tabbed Views (Simular to Skype), and I need to be able to populate the lists from the Database (SQLite).
My MainActivity.java :
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.speech.RecognizerIntent;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import static com.example.todo.Constants.*;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static String[] FROM = { _ID, TODO_TEXT, LOCATION, };
private static int[] TO = { R.id.todoTextView };
private static String ORDER_BY = ORDER + " DESC";
ListView taskListView;
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
public Button speakButton;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Context context = this;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAlert();
}
});
Cursor cursor = getEvents();
showEvents(cursor);
}
private void addEvent(String string) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
ContentValues values = new ContentValues();
values.put(ORDER, System.currentTimeMillis());
values.put(REMINDER_TEXT, string);
getContentResolver().insert(CONTENT_URI, values);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
void showAlert(){
final EditText reminderinput = (EditText) findViewById(R.id.reminderText);
AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
adb.setView(inflater.inflate(R.layout.dialog_new_reminder, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
// save reminder here
Editable reminderText = reminderinput.getText();
String reminderTextString = String.valueOf(reminderText);
addEvent(reminderTextString);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//it already cancels
}
});
adb.setTitle("Set a reminder");
AlertDialog ad = adb.create();
ad.show();
}
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
return managedQuery(CONTENT_URI, FROM, null, null, ORDER_BY);
}
private void showEvents(Cursor cursor) {
// Set up data binding
ListView mListView = (ListView) findViewById(R.id.listview);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.task_item, cursor, FROM, TO);
mListView.setAdapter(adapter);
}
#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) {
Intent intent = new Intent(this, AppSettings.class);
startActivity(intent);
}
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;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
/**
* 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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Important";
case 1:
return "Kinda Important";
case 2:
return "Not very Important";
}
return null;
}
}
}
Obviously, i have a Constants.java and also some layout files in the project.
Unfortunately, the app throws an error saying:
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
HELP!
So you have the listviews in your fragment and you are doing
ListView mListView = (ListView) findViewById(R.id.listview);
This finds the listview in activity_main and not the fragment.
You should populate the listviews in the fragment.
Call this in the fragment.
ListView mListView = rootview.findViewById(R.id.listview);
Cursor cursor = getEvents();
showEvents(cursor);
Please suggest me how implement Swipe left or right in my app? Is page viewer or gesture can be used. I get content for text view from string array when item clicked. I am new to app development.
My MainActivity xml
import android.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
{
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
boolean nightmode=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerlayout);
navList = (ListView)findViewById(R.id.navlist);
String[] versionName = getResources().getStringArray(R.array.version_names);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, versionName);
navList.setAdapter(adapter);
navList.setOnItemClickListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.opendrawer,R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
fragmentManager = getSupportFragmentManager();
OnSelectionChanged(0);
}
public void OnSelectionChanged(int position) {
DescriptionFragment descriptionFragment = (DescriptionFragment) getFragmentManager()
.findFragmentById(R.id.description_fragment);
if (descriptionFragment != null){
// If description is available, we are in two pane layout
// so we call the method in DescriptionFragment to update its content
descriptionFragment.setDescription(position);
} else {
DescriptionFragment newDesriptionFragment = new DescriptionFragment();
Bundle args = new Bundle();
args.putInt(DescriptionFragment.KEY_POSITION,position);
newDesriptionFragment.setArguments(args);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the backStack so the User can navigate back
fragmentTransaction.replace(R.id.fragment_container,newDesriptionFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
TextView textElement = (TextView) findViewById(R.id.version_description);
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.fragment_container);
if(nightmode) textElement.setTextColor(Color.WHITE);
switch(item.getItemId()){
case R.id.action_settings:
if (nightmode) {
mainLayout.setBackgroundResource(R.color.white);
textElement.setTextColor(Color.BLACK);
nightmode=false;
}else {
mainLayout.setBackgroundResource(R.color.background_color);
textElement.setTextColor(Color.WHITE);
nightmode=true;
}
break;
case android.R.id.home:
if (drawerLayout.isDrawerOpen(navList)){
drawerLayout.closeDrawer(navList);
}else{
drawerLayout.openDrawer(navList);
}
break;
case R.id.action_share:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
OnSelectionChanged(position);
drawerLayout.closeDrawer(navList);
}
}
My DescriptionFragment
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by sathi on 16-01-2016.
*/
public class DescriptionFragment extends Fragment {
final static String KEY_POSITION = "position";
int mCurrentPosition = -1;
String[] mVersionDescriptions;
TextView mVersionDescriptionTextView;
public DescriptionFragment(){
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mVersionDescriptions = getResources().getStringArray(R.array.version_descriptions);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/* DescriptionFragment descriptionFragment = new DescriptionFragment();
Object fromFragment = null;
Object toFragment=null;
descriptionFragment.addFragment(Fragment fromFragment, Fragment toFragment);*/
// If the Activity is recreated, the savedInstanceStare Bundle isn't empty
// we restore the previous version name selection set by the Bundle.
// This is necessary when in two pane layout
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(KEY_POSITION);
}
// FragmentTransaction fragmentTransaction = null;
// fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left);
View view = inflater.inflate(R.layout.fragment_description, container, false);
mVersionDescriptionTextView = (TextView) view.findViewById(R.id.version_description);
return view;
/* DescriptionFragment fragment1 = new DescriptionFragment();
(getSupportFragmentManager().beginTransaction().add(R.id.description_fragment, fragment1)
.add(R.id.description_fragment, fragment1).commit()){
}*/
}
public void addFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
public void replaceFragment(Fragment fromFragment, Fragment toFragment) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,toFragment, toFragment.getClass().getName());
transaction.hide(fromFragment);
transaction.addToBackStack(toFragment.getClass().getName());
transaction.commit();
}
private FragmentManager getSupportFragmentManager() {
return null;
}
#Override
public void onStart() {
super.onStart();
// During the startup, we check if there are any arguments passed to the fragment.
// onStart() is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method below
// that sets the description text
Bundle args = getArguments();
if (args != null){
// Set description based on argument passed in
setDescription(args.getInt(KEY_POSITION));
} else if(mCurrentPosition != -1){
// Set description based on savedInstanceState defined during onCreateView()
setDescription(mCurrentPosition);
}
}
public void setDescription(int descriptionIndex){
mVersionDescriptionTextView.setText(mVersionDescriptions[descriptionIndex]);
mCurrentPosition = descriptionIndex;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current description selection in case we need to recreate the fragment
outState.putInt(KEY_POSITION,mCurrentPosition);
}
}
I didn't understand if that actually what you trying to do but as i understood if you want the TextView moves automatically in one line to show the rest of it make this:
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true" />
and in code after defining it's view make this:
textView.setChecked(true);