Hi I am an amateur in Android, and I've got huge problem with using activity methods in my fragment class.
I would like to implement setContentView, findViewById and getMenuInflater. Unfortunately, I don't know how to do it.
public class WagaFragment extends Fragment{
private Spinner fromSpinner, toSpinner;
private EditText fromEditText, toEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**setContentView**(R.layout.activity_main);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.units, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fromSpinner = (Spinner) **findViewById**(R.id.spinner_from);
toSpinner = (Spinner) **findViewById**(R.id.spinner_to);
fromSpinner.setAdapter(adapter);
toSpinner.setAdapter(adapter);
fromEditText = (EditText) **findViewById**(R.id.editText_from);
toEditText = (EditText) **findViewById**(R.id.editText_to);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
toolbar.setTitleTextColor(Color.YELLOW);
}
#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;
}
public void konwertuj(View view) {
// Get the string from the Spinners and number from the EditText
String fromString = (String) fromSpinner.getSelectedItem();
String toString = (String) toSpinner.getSelectedItem();
double input = Double.valueOf(fromEditText.getText().toString());
// Convert the strings to something in our Unit enu,
Konwerter.Jednostka fromJednostka = Konwerter.Jednostka.fromString(fromString);
Konwerter.Jednostka toJednostka = Konwerter.Jednostka.fromString(toString);
// Create a converter object and convert!
Konwerter konwerter = new Konwerter(fromJednostka, toJednostka);
double result = konwerter.convert(input);
toEditText.setText(String.valueOf(result));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
}
In Fragments "contentView" (in your meanign) is defined in public View onCreateView procedure.
According to your code:
you have to use
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
<your control> = <Control type> view.findViewById(<control id>)
For MenuInflater try this:
MenuInflater inflater = getActivity().getMenuInflater();
Try at onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_name, container, false);
fromSpinner = (Spinner) view.findViewById(R.id.spinner_from);
return view;
}
Related
This is will run fragment in fragment that use viewpageAdapter.I want to pass data from fragment to tablayout fragment. i have try any method and still crash. i just want to passs once data to fragment in the tablayout.
First fragment. this line i want pass to tablayout fragment:-
specItem = getArguments().getString("spec_item");
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageUrl = getArguments().getString("image_url");
priceItem = getArguments().getString("price_item");
specItem = getArguments().getString("spec_item");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_view_details_item, container, false);
textPrice = (TextView) rootView.findViewById(R.id.textPrice);
image_Details = (ImageView) rootView.findViewById(R.id.image_Detail);
tabLayout = (TabLayout) rootView.findViewById(R.id.tablayout_id);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpage_id);
textPrice.setText(priceItem);
Picasso.get().load(imageUrl).into(image_Details);
ViewPageAdapter adapter = new ViewPageAdapter(getActivity().getSupportFragmentManager());
adapter.AddFragment(new FragmentSpecifications(), "Specification");
adapter.AddFragment(new FragmentReview(), "Review");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
Second fragment in tablayout, i dont know how to recieve:-
View rootView;
TextView textSpec;
String specItem;
public FragmentSpecifications() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_specification, container, false);
textSpec = (TextView) rootView.findViewById(R.id.textviewspec);
textSpec.setText();
return rootView;
}
Inside your FragmentSpecifications create a instance of the Fragment to send data to it, like this:
public static FragmentSpecifications newInstance(String priceItem) {
Bundle args = new Bundle();
args.putString("priceItem", priceItem);
FragmentSpecifications fragment = new FragmentSpecifications();
fragment.setArguments(args);
return fragment;
}
After that in same FragmentSpecifications override onCreate method and get value:
private String priceItem;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null)
priceItem = getArguments().getString("priceItem");
}
And finally when you add FragmentSpecifications do adapter pass the value:
adapter.AddFragment(FragmentSpecifications.newInstance(priceItem), "Specification");
I need to get the value of the spinner set in the first fragment and pass the value along to fragment 2. At the moment I'm just trying to set one text field in fragment 2 to the spinner's value, but later on I'll need to somehow have the fragment 1 spinner value match a unit like meters, and then for fragment 2 to be able to take that unit and a user input to then convert it into a second chosen user input.
In fragment 2 I have just typed out some 'bad' psuedo code to showcase what I'm trying to do:
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_page2));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {}
#Override
public void onTabReselected(TabLayout.Tab tab) {}
});
}
Fragment 1
public class Page1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.page1_fragment, container, false);
Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
return view;
}
Fragment 2
public class Page2Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View view = inflater.inflate(R.layout.page2_fragment, container, false);
fragment1Spinner = Page1Fragment.getSpinnerValue
TextView text = (TextView) view.findViewById(R.id.textView2);
text.setText(fragment1Spinner);
return view;
}
}
Add an onItemSelectedListener on your spinner to get the value selected in spinner. Store it in an variable and use setArguments and get arguments method of fragment to set and get the value..
Example:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// this line will get you the selected item of the spinner
String selectedValue = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
For setting the arguments to your fragment...considering you have a method in your fragment names newInstance. set this when navigating to second fragment.
Bundle bundle = new Bundle();
bundle.putString("selectedSpinnerItemKey", selectedSpinnerItemValue);
Fragment fragment = YourFragment.newInstance();
fragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContent, fragment);
transaction.commit();
Now getting the arguments in second fragment.
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (getArguments() != null)
{
String itemFromFirstFragment = getArguments().getString("selectedSpinnerItemKey");
}
}
I have a GridView in FragmentA containing all objects. When the user tap on each object, these objects are added into ListView of FragmentB.
Note that FragmentA and FragmentB are both in the same Activity, side by side.
I have tried using Bundle to send object from FragmentA to FragmentB but I was stucked as I have no idea how FragmentB is going to know that a new object has been added.
Bundle object is sent from ProductGridAdapter (under FragmentA) and receiver will be FragmentB where FragmentB will update the ListView for the latest objects added by FragmentA
Here is my code:
ProductGridAdapter.java
public class ProductGridAdapter extends ArrayAdapter<Product> {
private List<Product> productList;
private Context context;
public ProductGridAdapter(Context context, int resource,
List<Product> objects) {
super(context, resource, objects);
this.context = context;
this.productList = objects;
}
#Override
public int getCount() {
return ((null != productList) ?
productList.size() : 0);
}
#Override
public Product getItem(int position) {
return ((null != productList) ?
productList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(null == view) {
view = layoutInflater.inflate(R.layout.grid_product, null);
}
final Product product = productList.get(position);
if(product != null) {
final CardView productGridLayout = (CardView) view.findViewById(R.id.product_gridlayout);
final TextView productName = (TextView) view.findViewById(R.id.product_name);
final ImageView productIcon = (ImageView) view.findViewById(R.id.product_icon);
productName.setText(product.getName());
productIcon.setImageDrawable(product.getDrawable());
productGridLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentB fragment = new FragmentB();
Bundle bundle = new Bundle();
bundle.putSerializable("product", product);
fragment.setArguments(bundle);
}
});
}
return view;
}
}
FragmentA.java
public class FragmentA extends Fragment {
private GridView gridView;
private ProductGridAdapter productAdapter;
public FragmentA() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_product_display, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
productAdapter = new ProductGridAdapter(getActivity(), R.layout.fragment_product_display, getProductList());
gridView.setAdapter(productAdapter);
gridView.destroyDrawingCache();
gridView.setVisibility(GridView.INVISIBLE);
gridView.setVisibility(GridView.VISIBLE);
return rootView;
}
}
FragmentB.java
public class FragmentB extends Fragment {
private ListView listView;
private PaymentListAdapter paymentAdapter;
private LinearLayout button;
private ArrayList<String> arr;
public FragmentB() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_payment, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
paymentAdapter = new PaymentListAdapter(getActivity(), R.layout.fragment_payment, getProductList());
// button = (LinearLayout) rootView.findViewById(R.id.payment);
listView.setAdapter(paymentAdapter);
Bundle bundle = this.getArguments();
Product product = (Product) bundle.getSerializable("product");
return rootView;
}
you can have two common method in interface class in main activity, To update view in both fragment,When some changes happens in FragmentA you have to notify that changes to main activity then main activity should communicate to FragementB about that changes.try to do as like this,Hope this will help you.Happy Coding!
Ive got a Button in one of my Fragments. But it seems to be "not-clickable". There is no Log.d. Message when I click the Button (In another Fragment (Same onclicklistenercode) everything is fine.
For greater overview I added the whole Class and the part of my layout file which defindes the button.
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
View rootView=inflater.inflate(R.layout.fragment_listview, container, false);
ListView dataListListView = (ListView) rootView.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
return rootView;
}
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/deletelist"
android:id="#+id/button_deletelist_list"
android:layout_gravity="center_horizontal" />
You can not click the button because the root view of Fragment is not view, you returned rootView. The button is child view of view.
Change return rootView; to return view;.
It should work
//Remove rootView and return view instead of rootView
public class ListViewFragment extends Fragment {
DbHelper mydb;
Button buttondeletedb;
Button buttonexport;
private EditText roomnr;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listview, container, false);
Context context = getContext();
mydb = new DbHelper(context);
buttondeletedb = (Button) view.findViewById(R.id.button_deletelist_list);
buttonexport = (Button) view.findViewById(R.id.button_export);
String dataList = mydb.getAllElements();
String [] dataListArray = dataList.split("\n");
List<String> dataListFinal = new ArrayList<>(Arrays.asList(dataListArray));
ArrayAdapter<String> dataListAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.list_item_datalist,
R.id.list_item_datalist_textview,
dataListFinal);
// Change made here. replace view instead of rootView and remove rootView
ListView dataListListView = (ListView) view.findViewById(R.id.datalist);
dataListListView.setAdapter(dataListAdapter);
buttondeletedb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("buttondeletelist", "clicked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
mydb.deleteAll();
}
});
// Replace rootView with view.
return view;
}
}
Link between XML file and Class file of the Element (Button) is not there.Add this line in your onCreateView()
Button buttondeletedb = (Button) view.findViewById(R.id.buttonid);
I'm completely new to Android programming. I'm writing an where there are two Fragments: Query and Results. There is a Button and an EditText in the Query Fragment. When the user clicks on the Button, the results from the EditText should be displayed in the TextView that is present the Results Fragment.
Here is the Main Activity (Starting Point):
public class StartingPoint extends FragmentActivity
{
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
viewPager = (ViewPager)findViewById(R.id.pager);
viewPager.setAdapter(new FragmentsPagerAdapter(getSupportFragmentManager()));
}
}
Here is the QueryFragment.java:
public class QueryFragment extends Fragment
{
EditText queryET, endpointET;
Button execute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.query_fragment, container, false);
queryET = (EditText) view.findViewById(R.id.sparqlQueryET);
endpointET = (EditText) view.findViewById(R.id.sparqlEndpointET);
execute = (Button) view.findViewById(R.id.executeButton);
execute.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String query = queryET.toString();
String endpoint = endpointET.toString();
Query q = QueryFactory.create(query, Syntax.syntaxARQ);
q.setOffset(1);
QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint, query);
ResultSet rs = qe.execSelect();
StringBuffer results = new StringBuffer();
List<String> columnNames = rs.getResultVars();
while(rs.hasNext())
{
QuerySolution qs = rs.next();
for(String var: columnNames)
{
results.append(var +":");
if(qs.get(var) == null)
results.append("{null}");
else if (qs.get(var).isLiteral())
results.append(qs.getLiteral(var).toString());
else
results.append(qs.getResource(var).getURI());
results.append('\n');
}
results.append("----------------\n");
}
qe.close();
}
});
return view;
}
}
Here is the ResultsFragment:
public class ResultsFragment extends Fragment
{
TextView r;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
return view;
}
}
Now my question is how do I pass the result processed in the onClick method (of the QueryFragment), which is a String, to the ResultsFragment where the String would be displayed in a TextView?
Simple approach will be : Make public static String field in parent activity. onClick method will set info into this value, and onCreateView result fragment will try to take it from there.
onClick(View v){
MainActivity.myResultString = "result code";
}
and get it when you need it;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.results_fragment, container, false);
r = (TextView) view.findViewById(R.id.resultsTV);
r.setText(MainActivity.myResultString);
return view;
}
Something like this. Its not completed solution but can help you ) good luck.