I have one MainActivity and two fragments FGames and FGameDetail. I am trying to communicate between them so that when an item is clicked in the FGames it passes GameEntity to MainActivity and it updates the FGameDetail. I have separate layout created for phone and tablet.
In my MainActivity where I am controlling if the FGameDetail fragment exists in the layout update the view. but findFragmentById always returns null for both FGames and FGameDetails.
Here is my layout for Phones and Tablets
layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/games_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rao.igttest.MainActivity">
<fragment
android:id="#+id/fragment_fGames"
android:name="com.example.rao.igttest.Games.View.FGames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
layout-large-land\activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/fragment_fGames"
android:name="com.example.rao.igttest.Games.View.FGames"
android:layout_width="400dp"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/fragment_fGameDetail"
android:name="com.example.rao.igttest.Games.View.FGameDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity implements FGames.OnGameSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//FGames fGames = new FGames();
//getSupportFragmentManager().beginTransaction().add(R.id.games_container, fGames).commit();
}
#Override
public void onGameSelected(GameEntity gameEntity) {
FragmentManager fragmentManager = getSupportFragmentManager();
FGameDetail gameDetailFrag = (FGameDetail) fragmentManager
.findFragmentById(R.id.fragment_fGameDetail);
Fragment gameFrag = fragmentManager.findFragmentById(R.id.fragment_fGames);
if (gameDetailFrag == null) {
//TODO Open a new intent
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
FGameDetail fGameDetail = new FGameDetail();
fGameDetail.updateContent(gameEntity);
}
}
}
Your help and suggestions is much appreciated.
EDIT
FGAMES
#Override
public void initRecyclerView(List<GameEntity> gameEntities) {
gamesAdapter = new GamesAdapter(getActivity(), gameEntities);
rvGames.setAdapter(gamesAdapter);
rvGames.setLayoutManager(new LinearLayoutManager(getActivity()));
}
GamesAdapter
//Constructor
public GamesAdapter(Context context, List<GameEntity> gameEntities) {
layoutInflater = LayoutInflater.from(context);
this.data = gameEntities;
this.context = context;
}
#OnClick(R.id.row_container)
void rowClick(){
//I think as I am creating a new instance here as I dont have referencec to GamesPresenter in adapter as I am calling it directly from FGames
GamesPresenter gamesPresenter = new GamesPresenterImpl();
gamesPresenter.showGameDetail(data.get(getLayoutPosition()));
Toast.makeText(context, "itemClicked " + data.get(getLayoutPosition()), Toast.LENGTH_SHORT).show();
}
GamesPresenterImpl
#Override
public void showGameDetail(GameEntity gameEntity) {
GamesView gamesView = new FGames();
gamesView.onListItemClick(gameEntity);
}
FGames
#Override
public void onListItemClick(GameEntity gameEntity) {
OnGameSelectedListener mListener = new MainActivity();
mListener.onGameSelected(gameEntity);
}
public interface OnGameSelectedListener{
public void onGameSelected(GameEntity gameEntity);
}
MainActivity - OnGameSelected.
#Override
public void onGameSelected(GameEntity gameEntity) {
FragmentManager fragmentManager = getSupportFragmentManager();
FGameDetail gameDetailFrag = (FGameDetail) fragmentManager
.findFragmentById(R.id.fragment_fGameDetail);
Fragment gameFrag = fragmentManager.findFragmentById(R.id.fragment_fGames);
if (gameDetailFrag == null) {
} else {
// DisplayFragment (Fragment B) is in the layout (tablet layout),
// so tell the fragment to update
FGameDetail fGameDetail = new FGameDetail();
fGameDetail.updateContent(gameEntity);
}
}
Are you sure you are not doing new MainActivity().onGameSelected(object)?
If you using the Interactor fragment pattern, you must use the instance of the Activity you already have in the class.
Also, this line dont update the screen cause you creating a new instance of the fragment that will never be added:
FGameDetail fGameDetail = new FGameDetail();
fGameDetail.updateContent(gameEntity);
There is a instance already in screen so:
gameDetailFrag.updateContent(gameEntity);
I have 4 activities, when i press home button, it goes in background and when i open it from background, it starts from the activity from where i resume, but i want to open Launcher activity always because in my first activity password is set and i want the user to type password every time when the app is open
android:clearTaskOnLaunch="true"
android:finishOnTaskLaunch="true"
android:launchMode="singleInstance"
`
I have tried this code in Manifest,but it is also not working.
I have also tried this but unfortunately result is same
#Override
protected void onStop() {
sliderShow.stopAutoCycle();
super.onStop();
GalleryBrowserActivity.this.finish();
Log.d("value","value on Stop"+("position"));
}
UPDATE
Hi, I tried to solve this issue so that it can be useful for future too. May be my attempt will not suit in each and every application requirement but it can be helpful in many situations. This is a demo I tried using fragments and I assume this is the only possible way to achieve this requirement. Correct me if I am wrong anywhere. Here is the code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Fragment mCurrentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFragment(MainFragment.newInstance());
}
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
String backStackTag = fragment.getClass().getName();
boolean fragmentPoped = fragmentManager.popBackStackImmediate(backStackTag, 0);
if (!fragmentPoped) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragment, backStackTag);
if (backStackTag != null) {
fragmentTransaction.addToBackStack(backStackTag);
}
fragmentTransaction.commitAllowingStateLoss();
}
}
public void addFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
Fragment f = getSupportFragmentManager().findFragmentByTag(mCurrentFragment.getClass().getName());
if (f != null) {
fragmentTransaction.remove(f);
}
}
fragmentTransaction.add(R.id.frame, fragment, fragment.getClass().getName());
fragmentTransaction.commit();
mCurrentFragment = fragment;
}
public void replaceInMainFragment(Fragment fragment) {
if (mCurrentFragment != null && mCurrentFragment instanceof MainFragment) {
((MainFragment) mCurrentFragment).replaceFragment(fragment);
}
}
}
activity_main.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">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
MainFragment.java
public class MainFragment extends Fragment {
private View mView;
private Fragment mCurrentFragment;
public static MainFragment newInstance() {
MainFragment loginFragment = new MainFragment();
return loginFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_main, container, false);
Log.e("MainFragment", "onCreateView");
return mView;
}
#Override
public void onStart() {
super.onStart();
Log.e("MainFragment", "onStart");
addFragment(LoginFragment.newInstance());
}
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
String backStackTag = fragment.getClass().getName();
boolean fragmentPoped = fragmentManager.popBackStackImmediate(backStackTag, 0);
if (!fragmentPoped) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_main, fragment, backStackTag);
if (backStackTag != null) {
fragmentTransaction.addToBackStack(backStackTag);
}
fragmentTransaction.commitAllowingStateLoss();
}
}
public void addFragment(Fragment fragment) {
removeAllFragmentFromBackstack();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
if (mCurrentFragment != null) {
Fragment f = getActivity().getSupportFragmentManager().findFragmentByTag(mCurrentFragment.getClass().getName());
if (f != null) {
fragmentTransaction.remove(f);
}
}
fragmentTransaction.add(R.id.frame_main, fragment, fragment.getClass().getName());
fragmentTransaction.commit();
mCurrentFragment = fragment;
}
private void removeAllFragmentFromBackstack() {
FragmentManager fm = getActivity().getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
}
}
fragment_main.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">
<FrameLayout
android:id="#+id/frame_main"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
LoginFragment.java
public class LoginFragment extends Fragment {
private View mView;
public static LoginFragment newInstance() {
LoginFragment loginFragment = new LoginFragment();
return loginFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_login, container, false);
Log.e("LoginFragment", "onCreateView");
mView.findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).replaceInMainFragment(Fragment1.newInstance());
}
});
return mView;
}
}
fragment_login.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/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Login" />
</RelativeLayout>
Fragment1.java
public class Fragment1 extends Fragment {
private View mView;
public static Fragment1 newInstance() {
Fragment1 fragment1 = new Fragment1();
return fragment1;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_1, container, false);
mView.findViewById(R.id.btnFrag1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).replaceInMainFragment(Fragment2.newInstance());
}
});
return mView;
}
}
fragment_1.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/btnFrag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is Fragment 1" />
</RelativeLayout>
Fragment2.java
public class Fragment2 extends Fragment {
private View mView;
public static Fragment2 newInstance() {
Fragment2 fragment1 = new Fragment2();
return fragment1;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_2, container, false);
mView.findViewById(R.id.btnFrag2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return mView;
}
}
fragment_2.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/btnFrag2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is fragment 2" />
</RelativeLayout>
Hope it helps someone.
OLD
Then I think you need some hack. It will not directly accessible. Try calling 2nd activity when user press back button or any other option to go to the 2nd activity from 3rd activity. Hope it suits your app's requirement.
ThirdActivity.java
public class ThirdActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getBaseContext(), SecondActivity.class));
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
findViewById(R.id.btnJumpToThirdScreen).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), ThirdActivity.class));
}
});
}
}
OLD
Here is the demo I made just now. For this you need to define android:noHistory="true" in your manifest. Here is the sample code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnJump).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(), SecondActivity.class));
}
});
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ccc.stackoverflow">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:noHistory="true"></activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btnJump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My Launcher Activity Main" />
</RelativeLayout>
Try this demo. Also check removing noHistory flag from your Manifest. You can see the difference. Hope it helps you.
You should change your app design! Users do not want the app restarted every time they step out. They may lose some work.
You should rather use a sign-in dialog, or fragment, that is displayed above the current activity, every time user returns after app goes to background.
If you call the method:
finish();
In your life cycle methods it will work but It will have a disadvantage too:
The advantage is that when the user clicks "back" the activity will be destroyed and the user will have to put the password again.
The disadvantage is that when the user go to another app may be due to a click in the notification. After finishing using that other app, when the user clicks "back" he wont find your activity! He will have to go to a launcher and click your app icon again. This is not good for users for because they will have to click your app from launcher each time they leave the app.
BEST WAY
Declare a boolean in your Activity call it for example:
private boolean hasUserReturned=false;
Then in your onPause() method:
#Override
protected void onPause() {
super.onPause();
hasUserReturned=true;
}
Then in your onResume() nethod:
#Override
protected void onResume() {
super.onResume();
if(hasUserReturned){
recreate();
}
}
This will recreate your activity each time the user revisit your app. It handles "back button" clicks without removing your activity from backstack!
you should just follow life cycle of android,
when user press back button >> onStop() and onDestroy() called
when use press Home button >> onStop() called
when user again back to open application without more waiting and clean from stack(clear background data) >> called onRestart() called
and if user close the application and also remove application from background then it call >> onCreate()
Now just you find your point while following the life cycle of Android :-)
Solution One: apply code in onStop()
Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
OR
Solution Two: In AndroidManifest.xml file put android:launchMode="singleTask" in to all Activity
like above
<activity
android:name=".Activity.BookingConfirmClass"
android:label="#string/string_confrim_booking"
android:launchMode="singleTask"
android:parentActivityName=".Activity.HotelDetailsClass"
android:screenOrientation="portrait" />
I could suggest you one approach,
Make all your activities extend from one BaseActivity
Add a variable in BaseActivity
public static boolean HAS_RESUMED_FROM_ACTIVITY=false;
and then override startActivity in your BaseActivity like
#Override
startActivity(Intent intent){
HAS_RESUMED_FROM_ACTIVITY=true;
super.startActivity(intent);
}
Now in onResume of your activities you
#Override
protected void onResume(){
if(!BaseActivity.HAS_RESUMED_FROM_ACTIVITY){
//show your lock screen
}
super.onResume();
}
I have the activity that have fragment. Now I have button that open the fragment. I am wondering how I can use the same button for openning and closing fragment?
My code is:
public class MainActivity extends AppCompatActivity {
FragmentTransaction fTrans;
Button reg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (Button) findViewById(R.id.reg);
frag1 = new Fragment1();
}
public void openFragment(View v){
fTrans = getFragmentManager().beginTransaction();
fTrans.add(R.id.frgmCont, frag1);
fTrans.commit();
}
}
XML file of MainActivity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.myapplication5.MainActivity">
<Button
android:id="#+id/reg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Registration"
android:background="#drawable/add_btn"
android:layout_margin="10dp"
android:onClick="openFragment"
/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
And here is the fragment:
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, null);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
}
}
change your activity code to this
public class MainActivity extends AppCompatActivity {
FragmentTransaction fTrans;
Button reg;
boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
reg = (Button) findViewById(R.id.reg);
frag1 = new Fragment1();
}
public void openFragment(View v){
fTrans = getFragmentManager().beginTransaction();
if(flag) {
fTrans.remove(frag1);
} else {
fTrans.add(R.id.frgmCont, frag1);
}
flag = !flag;
fTrans.commit();
}
}
I'm trying to start a fragment from my main activity, but somehow the fragment is not showing up. Can someone help me with this?
Here is my code:
public class Main extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.action_menu);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.action_menu){
Log.d("--", "menu clicked");
MenuFragment newFragment = new MenuFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
main activity layout:
<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:id="#+id/main_rl" >
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/action_menu" android:text="Menu"/>
</RelativeLayout>
and my fragment Class:
public class MenuFragment extends Fragment{
final String TAG=this.getClass().getSimpleName();
private GridView grid;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView;
Log.d(TAG, "Hello from Fragment");
mView=inflater.inflate(R.layout.menu_fullscreen, null);
initWidgets(mView);
return mView;
}
private void initWidgets(View mView) {
grid=(GridView) mView.findViewById(R.id.menu_fullscreen_grid);
}
}
you cannot replace what you put in setContentView(R.layout.main); if main.xml is hardCoded...(xml file). with
transaction.replace...
You may use fragmentActivity without setContentView(R.layout.main)
I am using fragments,I have an edittext in fragment and I want to get value in main activity.
This is my fragment layout
<?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"
android:orientation="vertical"
android:background="#878787" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="dfgdfgdf"
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="#+id/user_name"/>
<EditText
android:id="#+id/message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:text="Gönder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="getFromUser"
android:layout_marginTop="40dp"
/>
</RelativeLayout>
I am loading fragment with this function:
public void startChat(JsonObject user) {
FrameLayout layout = (FrameLayout)findViewById(R.id.container);
layout.setVisibility(View.VISIBLE);
Bundle bundle = new Bundle();
bundle.putString("name", user.get("name").getAsString());
sendTo=user.get("username").getAsString();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ConversationFragment conv = new ConversationFragment();
conv.setArguments(bundle);
fragmentTransaction.add(R.id.container, conv);
fragmentTransaction.commit();
viewPager.setVisibility(View.GONE);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayHomeAsUpEnabled(true);
}
And this is my fragment class
public class ConversationFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String name = getArguments().getString("name");
View rootView = inflater.inflate(R.layout.fragment_conversation, container, false);
TextView username=(TextView)rootView.findViewById(R.id.user_name);
username.setText(name);
return rootView;
}
}
As you can see when press the button main activity runs "getFromUser" function.I want to get edittext value in this function.How can I do this ?
It's always the same procedure for these things. You can't access a fragment's views just like that. You need a callback method.
Add this code to ConversationFragment:
private OnGetFromUserClickListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnGetFromUserClickListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnGetFromUserClickListener");
}
}
public void getFromUser(View v) {
if (mListener != null) {
EditText edit = (EditText)findViewById(R.id.message);
mListener.getFromUser(edit.getText().toString());
}
}
public interface OnGetFromUserClickListener {
void getFromUser(String message);
}
Make your MainActivity implement this interface. Replace getFromUser() inside MainActivity with:
public void getFromUser(String message) {
sendMessage(message);
}
Done.
Edit:
Actually, using the XML-onClick attribute is currently bugged (see onClick inside fragment called on Activity): It links to the activity instead of the fragment. You have to set the click listener programmatically to make sure the code won't break at some point in the future. So give the button an ID inside the XML (e.g. get_from_user) and add this code to onCreateView inside ConversationFragment:
v.findViewById(R.id.get_from_user).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.get_from_user) {
getFromUser(v);
}
}
});
Using this code vastly decouples the activity and the fragment from each other.
I resolved this problem.
public void getFromUser(View view) {
ConversationFragment fragment1 = (ConversationFragment)getSupportFragmentManager().findFragmentById(R.id.container);
View frag=fragment1.getView();
EditText editText1 =(EditText) frag.findViewById(R.id.message);
String message=editText1.getText().toString();
sendMessage(message);
}
Now I can get edittext value from fragment.