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.
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!
I am trying to use a floating action button in a fragment to bring up a dialog to create a new post. The issue I am having is that I get an error on this line of code:
popAddPost = new Dialog(this);
The error states that:
Dialog (android.content.context) in Dialog cannot be applied to (com.comhar.firebaseapp.Fragments.ForumFragment)
I have tried using a few solutions i found online but none have worked
ForumFragment.java
public class ForumFragment extends Fragment {
Dialog popAddPost;
public ForumFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_forum, container, false);
iniPopup();
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
popAddPost.show();
}
});
return view;
}
private void iniPopup() {
popAddPost = new Dialog(this);
popAddPost.setContentView(R.layout.popup_add_post);
popAddPost.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popAddPost.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT,Toolbar.LayoutParams.WRAP_CONTENT);
popAddPost.getWindow().getAttributes().gravity = Gravity.TOP;
}
}
fragment_forum.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.ForumFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="forum" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="20dp"
android:src="#drawable/nep_post" />
</FrameLayout>
The app will not run as I am recieving the error:
error: incompatible types: ForumFragment cannot be converted to Context
any advice would be greatly appreciated!
You should init the dialog with an proper context, it can be the context where the Fragment resides or could be the activity which holds the Fragment. So, replace this line:
popAddPost = new Dialog(this);
by this:
popAddPost = new Dialog(getActivity());
Update your iniPopup() method like this:
private void iniPopup() {
popAddPost = new Dialog(getActivity());
popAddPost.setContentView(R.layout.activity_login);
popAddPost.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popAddPost.getWindow().setLayout(Toolbar.LayoutParams.MATCH_PARENT, Toolbar.LayoutParams.WRAP_CONTENT);
popAddPost.getWindow().getAttributes().gravity = Gravity.TOP;
}
Let me know in case of any query.
I am trying to setup a onclicklistner on a dialog button. If the listener is set using
bnxt.setOnClickListener(new x());
the app works as expected but if the below given 2nd implementation is used, the app crashes. Any hint or help is highly appreciated.
bnxt.setOnClickListener(new OnClickListener() { ...
Supplied code:
class x implements OnClickListener {
x() {
}
public void onClick(View v) {
if (listener != null) {
final Dialog dialog = new Dialog(getActivity());
FancyButton m_no = (FancyButton) dialog.findViewById(R.id.b_no);
m_no.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
}
public View onCView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_x, container, false);
final FancyButton bnxt = (FancyButton) view.findViewById(R.id.btn_popup);
//bnxt.setOnClickListener(new x());
bnxt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (listener != null) {
final Dialog dialog = new Dialog(getActivity());
FancyButton m_no = (FancyButton) dialog.findViewById(R.id.b_no);
m_no.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
return view;
}
There is no problem with using a nested onClicklistener. Below is the sample code. Kept layout as simple just to test.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
view.findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_view);
dialog.findViewById(R.id.dialog_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Dialog btn clicked", Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
});
return view;
}
fragment_test.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="match_parent"
android:layout_height="match_parent"
tools:context=".TestActivityFragment">
<Button
android:id="#+id/btn1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="btn1"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:text="btn2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#id/btn1" />
</android.support.constraint.ConstraintLayout>
dialog_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/dialog_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dialog BTn" />
</android.support.constraint.ConstraintLayout>
So the title explains it all. I have a dialogfragment that currently pops up and I want to add a do not show checkbox to it and then obviously implement that check and not show if it was checked. I know there is a .setSingleChoiceItems, but I am not entirely sure on what would be going in there as it isn't really an item I would add somewhere. But then again I could probably be wrong as I am just getting into Android development.
Dialogfragment java
public class WifivsDataDialog extends DialogFragment {
#
Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_box)
.setPositiveButton(R.string.WiFi, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
}
})
.setNegativeButton(R.string.Cell_Data, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Here is the code calling it in my MainActivity.java
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "dialog_layout");
myDiag.setCancelable(false);
The accepted answer works, but it doesn't look like the normal material design system dialog, which is what I wanted.
Here's an option using a custom view layout to hold just the text and checkbox (with padding that matches material design), and allow the AlertDialog to manage the buttons.
no_location_dialog.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="24dp"
android:paddingRight="12dp">
<TextView
android:id="#+id/no_location_text"
style="?android:attr/textAppearance"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="14dp"
android:paddingBottom="6dp"
android:text="#string/main_nolocation"
android:textSize="16sp"
android:autoLink="all"
android:linksClickable="true"></TextView>
<CheckBox
android:id="#+id/location_never_ask_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_never_ask_again" />
</LinearLayout>
And the code for setting up the AlertDialog:
private Dialog createNoLocationDialog() {
View view = getActivity().getLayoutInflater().inflate(R.layout.no_location_dialog, null);
CheckBox neverShowDialog = (CheckBox) view.findViewById(R.id.location_never_ask_again);
neverShowDialog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Save the preference
PreferenceUtils.saveBoolean(getString(R.string.preference_key_never_show_location_dialog), isChecked);
}
});
Drawable icon = getResources().getDrawable(android.R.drawable.ic_dialog_map);
DrawableCompat.setTint(icon, getResources().getColor(R.color.theme_primary));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.main_nolocation_title)
.setIcon(icon)
.setCancelable(false)
.setView(view)
.setPositiveButton(R.string.rt_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUEST_NO_LOCATION);
}
}
)
.setNegativeButton(R.string.rt_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Ok, I suppose we can just try looking from where we
// are.
mMapFragment.mController.onLocation();
}
}
);
return builder.create();
}
It looks like this:
Here's the full code in a commit on Github - https://github.com/OneBusAway/onebusaway-android/commit/98135b66b0be5b73187e0148bef5d308c42a9fbe.
The DialogFragment class
public class WifivsDataDialog extends DialogFragment implements View.OnClickListener {
private CheckBox checkBox;
private Button button1;
private Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.wifi_dialog, container);
checkBox = (CheckBox) mainView.findViewById(R.id.checkBox);
button1 = (Button) mainView.findViewById(R.id.button1);
button2 = (Button) mainView.findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// Store the isChecked to Preference here
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("DONT_SHOW_DIALOG", isChecked);
editor.commit();
}
});
return mainView;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
// Do wifi stuff here
break;
case R.id.button2:
// Do cellular stuff here
break;
}
}
}
The Layout xml wifi_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some information to be displayed to human"
android:id="#+id/textView" android:textSize="30dp"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do now show this dialog again."
android:id="#+id/checkBox"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WiFi"
android:id="#+id/button1" android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CELL"
android:id="#+id/button2"/>
</LinearLayout>
</LinearLayout>
And on your Activity or where ever you display the dialog, check the preference set by user before displaying the dialog. Something like below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
new WifivsDataDialog().show(getFragmentManager(), "WiFi");
}
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);
}
}