I'm trying to use setRetainInstance() but it seems not working for me! =(.
I simplified the problem to the easiest version:
I have a fragment with a TextView and a Button.
The initial text of the TextView is "I'm waiting" when the button is pressed the text changes to "Hello!"
That is my code:
The fragment:
public class SayHelloFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.setText("Hello!");
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
The Activity:
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/say_hello_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.example.retaintext.SayHelloFragment" />
The Fragment's layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I'm Waiting"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
But when I play it, press the button and change the device's orientation the text becomes reset.
What am I missing? How can I solve it? Thanks!
You are missing that onCreateView runs after the rotation again and inflates the default view with the default text again.
You need to restore the state of your views manually, e.g.:
public class SayHelloFragment extends Fragment {
private String mText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
if (mText != null)
text.setText(mText);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mText = "Hello!";
text.setText(mText);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
Related
Hey all I am having a little bit of an issue with trying to call a fragment that has the videoview within it into my current fragment page.
When I click on the test button I set up it goes through the code without error but never shows the video fragment - I even gave it a background color of red so I could see it load into my current view.
My goal here is just to send a parameter of the video path to the video fragment videoview player and start playing it.
videoPlay.java
public class videoPlay extends Fragment {
public videoPlay(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragvideoplay, container, false);
MediaController mc= new MediaController(getActivity());
VideoView view = (VideoView)rootView.findViewById(R.id.videoView);
String path = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/sddir/Bubble Guppies.mp4";
view.setVideoURI(Uri.parse(path));
view.setMediaController(mc);
view.start();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
}
}
_fragvideoplayer.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<VideoView
android:id="#+id/videoView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
FragMovies.java:
public class FragMovies extends Fragment {
public FragMovies(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragmovies, container, false);
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
container.findViewById(R.id.webView).setVisibility(View.GONE);
container.findViewById(R.id.pBar1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
container.findViewById(R.id.pBar1).setVisibility(View.GONE);
container.findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setAllowContentAccess(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setLoadsImagesAutomatically(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setBuiltInZoomControls(false);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setDisplayZoomControls(false);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.getSettings().setSupportZoom(false);
view.setHorizontalScrollBarEnabled(false);
view.setVerticalScrollBarEnabled(false);
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("https://www.bing.com/");
return rootView ;
}
}
_fragmovies.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainLayout">
<ProgressBar
android:id="#+id/pBar1"
android:layout_width="93dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true"
android:layout_marginStart="950px"
android:layout_marginLeft="950px" />
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</LinearLayout>
Main_activity.java:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
PagerAdapter pagerAdapter;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getViews();
//adapter setup
pagerAdapter = new com.example.telluridetainment.PagerAdapter(getSupportFragmentManager());
//attaching fragments to adapter
pagerAdapter.addFragment(new FragMovies(),"Movies");
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
//setting icons
tabLayout.getTabAt(0).setIcon(R.drawable.ic_movie_white_24dp);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new MyClass());
}
public class MyClass implements View.OnClickListener {
#Override
public void onClick(View v) {
videoPlay myfragment = new videoPlay();
//pass data
Bundle bundle = new Bundle();
bundle.putString("KEY","DATA");
myfragment.setArguments(bundle);
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentManager.addToBackStack(null);
fragmentManager.replace(R.id.viewPager, myfragment).commit();
}
}
private void getViews() {
tabLayout = findViewById(R.id.mTabLayout);
viewPager = findViewById(R.id.viewPager);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="2000px"
android:layout_height="1200px"
tools:context=".MainActivity">
<Button
android:id="#+id/button0"
android:layout_width="200dp"
android:layout_height="152dp"
android:text="Button"
android:textColor="#B71C1C" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/appbarLayout"
tools:ignore="SpeakableTextPresentCheck">
</android.support.v4.view.ViewPager>
</RelativeLayout>
The path to the movie is correct. And the movie is there in the "external" SD card path. Clicking around on the new fragment (videoPlay) yields no video menu (play, remind, pause...) so its not there.
Any help would be great!
This question already has answers here:
findViewById in Fragment
(37 answers)
Closed 6 years ago.
I'm making an android app and I have a button that won't react when I press it. The button is supposed to bring up an alertdialog box. I'm very confused as I have an OnClickListener and the dialog box is instantiated.
Here is the code from the Java file:
public class tab1Expenses extends Fragment {
Button btnEx;
public class button extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1expense);
btnEx = (Button)findViewById(R.id.btnEx);
btnEx.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
View view = LayoutInflater.from(button.this).inflate(R.layout.add_ex, null);
AlertDialog.Builder add = new AlertDialog.Builder(button.this);
add.setView(view);
add.setCancelable(true)
.setTitle("Enter Expense:")
.setMessage("Expense Name:")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = add.create();
dialog.show();
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1expense, container, false);
return rootView;
}
}
And here is my XML file that is related to the java file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ojemz.expensetracker.tab1Expenses$button"
android:background="#android:color/darker_gray">
<Button
android:text="Add Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnEx"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:width="800dp"
android:textAppearance="#style/TextAppearance.AppCompat.Widget.Switch"
android:background="#android:color/black"
android:textColor="#android:color/holo_green_light" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="17dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- TextView and other stuff -->
</LinearLayout>
</ScrollView>
You're doing it wrong!
The button class extending Activity has no reason to exist here.
If you simply want to get some onClick callbacks just do the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1expense, container, false);
btnEx = (Button)rootView.findViewById(R.id.btnEx);
btnEx.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
View view = LayoutInflater.from(button.this).inflate(R.layout.add_ex, null);
AlertDialog.Builder add = new AlertDialog.Builder(tab1Expenses.this.getActivity());
add.setView(view);
add.setCancelable(true)
.setTitle("Enter Expense:")
.setMessage("Expense Name:")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog = add.create();
dialog.show();
}
});
return rootView;
}
Don't forget to remove your "button" inner class.
Side note
You should rename your tab1Expenses Fragment class to Tab1Expenses in order to distinguish between instances and classes.
Please refer to Java naming conversions.
How to go one Fragment to another when I will click on TextView Id?
Error shows:
java.lang.ClassCastException: com.example.tripigator.Overview cannot be cast to android.app.Activity.
and error comes from these lines :
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
So please anybody help me how to move from one fragment to another by clicking text item.
ProjectOverview class :
public class ProjectOverview extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_overview);
initialingpaging();
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
}
private void initialingpaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Overview.class.getName()));
fragments.add(Fragment.instantiate(this, Highlight.class.getName()));
mPageAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPageAdapter);
}
}
Two Fragment Classes:
public class Overview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.overview,container,false);
}
}
public class Highlight extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.highlight,container,false);
}
}
Layout Interface:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/project_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="65dp"
android:gravity="center" >
<TextView
android:id="#+id/txt_overview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Overview" />
<TextView
android:id="#+id/txt_highlite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Highlight" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
You can't initiate the fragment using Intent.Try this it helps.
Fragment fragment = null;
FragmentManager frgManager;
FragmentTransaction ft;
fragment = new Overview();
ft = frgManager.beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
If you use View-Pager
your_ViewPager.setCurrentItem(position)
you should not use intent in fragment to move another fragment
and check this for whole example http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
use this.
((yourfragmentActivity) getActivity()).setCurrentItem(1,//desired activity 0=first 1= second and so on
true);
insted
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
I have created a layout that contains a listView, the view is populated with multiple similar elements in the onCreateView function from a Fragment, the view is populated in the CustomAdapter extends BaseAdapter. In each element of the listView I have a button for which I want to implement a onClickListener. When the button is clicked I want to switch to another view, something similar to viewing comments on the GooglePlus mobile app.
I have tried doing so this way in the CustomAdapter:
public void setOnClickComment(View view) {
final ImageButton btn = (ImageButton)view.findViewById(R.id.addComment);
if (btn != null) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("ONCLICK", "I just clicked this shit" + btn.getTag());
manager.beginTransaction()
.replace(R.id.feedLayout, new CommentFragment()).commit();
}
});
} else {
Log.d("CLICK", "ESTE NULL");
}
}
The manager is a FragmentManager and it's passed from the fragment to the CustomAdapter constructor. I can see the Log in LogCat but that's it nothing else happens, the tag of the button is the position of the element.
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/feedLayout"
>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
And in the fragment I inflate the above layout:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout linear = (LinearLayout) inflater.inflate(R.layout.swipe_screen_left, container, false);
view = (ListView) linear.getChildAt(0);
adapter = new CustomAdapter(getActivity(), data, getFragmentManager());
view.setAdapter(adapter);
return linear;
}
i'm trying to create a fragment dialog and need the full space to display information. so i want to disable the titlebar. But after i disabled it the isn't maximized in width anymore.
public class ArticleSearchFragment extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, getTheme());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.article_search, container, false);
...
}
And the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/searchField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Ean / Name / Produkt Nummer"
android:completionThreshold="1" />
<Button
android:id="#+id/cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/cancel" />
</LinearLayout>
put this code in your onCreateView() of dialog fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_image, null);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
It will remove title bar from Dialog Fragment