I am using the default Navigation Drawer in android studio and I have a dynamically created fragment and use TabLayout to run it. It will run normally but as I try to load the same fragment from the navigation drawer i run into error. Please see below:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Introduction extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final RelativeLayout relativeLayout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
relativeLayout.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
final ImageView introImage = new ImageView(getActivity());
introImage.setId(R.id.introImageId);
introImage.setImageResource(R.drawable.introduction);
introImage.setAnimation(AnimationUtils.loadAnimation(this.getContext(), android.R.anim.slide_out_right));
introImage.setPadding(100, 100, 100, 100);
final TextView introText = new TextView(getActivity());
introText.setText(R.string.introduction_text);
// introText.setTextAppearance(android.R.style.TextAppearance_Medium);
introText.setTextSize(20);
introText.setPadding(25,25,25,25);
introText.setTextColor(ContextCompat.getColor(this.getContext(), R.color.colorPrimary));
params.addRule(RelativeLayout.BELOW, introImage.getId());
introText.setAnimation(AnimationUtils.loadAnimation(this.getContext(),android.R.anim.slide_in_left));
relativeLayout.addView(introText,params);
relativeLayout.addView(introImage);
return relativeLayout;
}
}
But as I try to load it from Navigation drawer I get an error Error:(115, 62) error: incompatible types: Introduction cannot be converted to Fragment
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fn = getFragmentManager();
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_introduction) {
fn.beginTransaction().replace(R.id.content_frame,new Introduction()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
TabPagerAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter {
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount=numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Introduction tab1= new Introduction();
return tab1;
default:
return null;
}
}
I replaced getFragmentManager(); with getSupportFragmentManager(); and its working
// FragmentManager fn = getFragmentManager();
FragmentManager fn = getSupportFragmentManager();
Related
this code was working perfectly when i was using navigation drawer activity after making some changes to my project and start using bottom navigation activity it just wont work and give my the error of incompatible types .. i tried every possible answer related to this issue but i get the same error
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity {
private TextView mTextMessage;
SearchFragment searchFragment;
private FrameLayout Eframe;
private HomeFragment homeFragment;
private BottomNavigationView eNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Eframe = findViewById(R.id.main_frame);
searchFragment = new SearchFragment();
setFragment(searchFragment);
eNav = findViewById(R.id.Nav);
eNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Search:
> setFragment(searchFragment);
return true;
case R.id.Home:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.Profile:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Menu:
mTextMessage.setText(R.string.title_notifications);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}
}
instead of extends AppCompatActivity
write extends Fragment.
I have FAB and TabLayout with viewpager in mainAcitivty. I want to update fragment of viewpager when user provide input by FAB. Trying to send data via Bundle but always Bundle is null while receiving from fragment.
I think my problem is in receiving data. To which fragment method I should use to receive data?
Here is my MainActivity
package com.example.shahalam.rvfabvptl;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText title, description;
FloatingActionButton fab;
ViewPager mPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_box,null);
title = mView.findViewById(R.id.titleDialogBox);
description = mView.findViewById(R.id.descriptionDialogBox);
Button btnOK = mView.findViewById(R.id.btnOk);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
final FragmentOne fragOne = new FragmentOne();
Bundle mBundle = new Bundle();
mBundle.putString("title", title.getText().toString());
mBundle.putString("description", description.getText().toString());
//PASS OVER THE BUNDLE TO OUR FRAGMENT
FragmentOne myFragment = new FragmentOne();
myFragment.setArguments(mBundle);
ft.add(R.id.linearLayoutFragmentOne,fragOne);
ft.commit();
dialog.cancel();
}
});
}
});
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(mPager);
}
}
And here is my Fragment class:
package com.example.shahalam.rvfabvptl;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
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 android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class FragmentOne extends Fragment {
public FragmentOne() {
}
RecyclerView fragOneRecyclerView;
List<MyDataModel> myDataModels = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one,container,false);
fragOneRecyclerView = view.findViewById(R.id.fragmentOneRecyclerView);
fragOneRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final RecyclerViewAdapter adapterFragmentOne = new RecyclerViewAdapter(getContext(),myDataModels);
fragOneRecyclerView.setAdapter(adapterFragmentOne);
Bundle mBundle =getArguments();
String title="if Bundle is null", description="No description";
if (mBundle != null) {
title = this.getArguments().getString("title");
description = this.getArguments().getString("description");
}
MyDataModel mOne4 = new MyDataModel(title,description);
myDataModels.add(mOne4);
adapterFragmentOne.notifyDataSetChanged();
return view;
}
}
You are creating two different objects of your Fragment FragmentOne ,
and setting the bundle to object myFragment and passing another fragment object fragOne in FragmentTransition. which is wrong , use
the below code.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne fragOne = new FragmentOne();
Bundle mBundle = new Bundle();
mBundle.putString("title", title.getText().toString());
mBundle.putString("description", description.getText().toString());
//PASS OVER THE BUNDLE TO OUR FRAGMENT
fragOne.setArguments(mBundle);
ft.add(R.id.linearLayoutFragmentOne,fragOne);
ft.commit();
dialog.cancel();
Once the user selects an item from a list in another fragment it brings you to this fragment. And I'm having issues trying to save the users rating that was selected. when the user goes back it should be the same rating that was previously selected.
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.Arrays;
public class infoFragment extends Fragment {
TextView degrees;
ImageView image;
String stringtext;
String [] hold;
private RatingBar rating;
SharedPreferences wmbPreference1;
SharedPreferences.Editor editor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.info_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
image = (ImageView) view.findViewById(R.id.imageView);
why can i not use "this"
rating =((RatingBar) view.findViewById(R.id.ratingBar)).setOnRatingBarChangeListener(this);
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
degrees =(TextView)view.findViewById(R.id.textView);
}
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
editor = wmbPreference1.edit();
editor.putInt("numStars", numStars);
editor.commit();
int ratings = wmbPreference1.getInt("numStars", 0);
}
public void setText(final String string) {
Character[] hold;
if(string == "apple"){
String[] word = { " A \n", "B\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.APPLE);
}
Should I call onRatingChanged within the conditional statement for it to save?
if(string == "orange"){
String[] word = { " AA\n", "AB\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.bruce);
}
}
public void sentText(){
new MyTask().execute();
}
private class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
Bundle b = getArguments();
stringtext = b.getString("text");
return null;
}
protected void onPostExecute(String result){setText(stringtext);
}
}
}
Your Fragment should implement OnRatingBarChangeListener:
public class infoFragment extends Fragment implements OnRatingBarChangeListener
The other thing is that setOnRatingChangeListener does not return a value, so you can't assign the return value to rating as you did.
You should do:
rating = (RatingBar) view.findViewById(R.id.ratingBar);
rating.setOnRatingBarChangeListener(this);
I'm Implementing Flipboard Animation in my activity pageIndicatorActivity its showing an error i.e The method Page(NoteViewAdapter) in the type FlipViewController is not applicable for the arguments
(PageIndicatorActivity.NoteViewAdapter)
this is the error I'm facing
here is my code
package com.horizontalscrollviewwithpageindicator;
import java.util.ArrayList;
import com.aphidmobile.flip.FlipViewController;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
ArrayList<String> notes = new ArrayList<String>();
notes.add("Come");
notes.add("On");
notes.add("Flip");
notes.add("Me");
//You can also use FlipViewController.VERTICAL
FlipViewController flipView = new FlipViewController(this, FlipViewController.HORIZONTAL);
//We're creating a NoteViewAdapter instance, by passing in the current context and the
//values to display after each flip
flipView.Page(new NoteViewAdapter(this, notes));
setContentView(flipView);
}
public abstract class NoteViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<String> notes;
public NoteViewAdapter(Context currentContext, ArrayList<String> allNotes) {
inflater = LayoutInflater.from(currentContext);
notes = allNotes;
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout = convertView;
if (convertView == null) {
layout = inflater.inflate(R.layout.activity_main, null);
}
//Get's value from our ArrayList by the position
String note = notes.get(position);
TextView tView = (TextView) layout.findViewById(R.id.note);
tView.setText(note);
return layout;
}
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
App need to open some websites when i touch buttons. There are 2 tabs (2 fragments) with different buttons (1 button = 1 link)
When i click a Button that need to open WebView (to open a link) application crash. I think, mistake is somewhere in AFragment.java
main.java (it's good 99,9%)
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
public static Context appContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PTab = actionbar.newTab().setText("One");
ActionBar.Tab DTab = actionbar.newTab().setText("Two");
Fragment OneFragment = new AFragment();
Fragment TwpFragment = new BFragment();
PTab.setTabListener(new MyTabsListener(OneFragment));
DTab.setTabListener(new MyTabsListener(TwoFragment));
actionbar.addTab(PTab);
actionbar.addTab(DTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
//Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
AFragment.java:
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class AFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
SavedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.afragment, container, false);
}
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
}
openPage.class:
import android.webkit.WebView;
import android.app.Activity;
import android.os.Bundle;
public class openPage extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://safhkalfsd.com");
}
}
Layouts are fine 99,99%
i put
android:onClick="openIt"
in afragment.xml inside Button
THANK YOU
SOLVED!
I need to put:
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
in MainActivity, not in 'AFragment'.