i am creating a tab view in that when a button is clicked it must move to another screen when i try to implement it using the above code it is changing to another screen but the button is still visible with next screen and i want next screen should cover entire screen
public class Tab1Fragment extends Fragment {
LinearLayout mLayout;
/** (non-Javadoc)
* #see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment mFragment = new third_fragment_view();
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, mFragment);
ft.addToBackStack(null);
ft.commit();
}
});
return theLayout;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#00bfff"
android:id="#+id/container1" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
The Ui to cover the entire Screen dn't use Fragments.Use Intents
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(thisactivity.class,targetactivity.class);
startActivity(intent);
}
});
Related
I am building a quiz app with three questions and therefore I have 6 Fragments but I would like to disable the default transition from one fragment to another, how can I achieve this? I already disabled that you can swipe between the fragments, you have to click a button to get to the next fragment, but there is still somehow a swiping transition after clicking the button. I searched for this but there was never an answer that would fit my problem. Here is one fragment example:
public class FragmentQuestion1 extends Fragment {
private Button btnNavFrag1;
private EditText editText;
private ProgressBar m_bar;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_question_1, container, false);
btnNavFrag1 = view.findViewById(R.id.btn_question1);
editText = view.findViewById(R.id.edit_text_question_1);
editText.addTextChangedListener(new NumberTextWatcher(editText));
m_bar = view.findViewById(R.id.progress_bar_question_1);
btnNavFrag1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((GameActivity)getActivity()).setViewPager(2);
}
});
return view;
}
// Method that is used so the countdown starts when the user gets to this fragment
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
startCountdownTimer();
}
}
// Countdown 17 seconds
int i = 0;
private void startCountdownTimer() {
m_bar.setProgress(i);
final int totalMsecs = 17 * 1000; // 17 seconds in milli seconds
int callInterval = 100;
/** CountDownTimer */
new CountDownTimer(totalMsecs, callInterval) {
public void onTick(long millisUntilFinished) {
int secondsRemaining = (int) millisUntilFinished / 1000;
float fraction = millisUntilFinished / (float) totalMsecs;
// progress bar is based on scale of 1 to 100;
m_bar.setProgress((int) (fraction * 100));
}
public void onFinish() {
}
}.start();
}
Because you are using a viewPager, you could use a library like this which lets you add a transformer (some sort of effect) to the viewPager when going to the next fragment. I'd recommend the ZoomOutTranformer for your use-case. If the transition is not what you expect you can always extend from that class and override the transition so it's more to your liking.
ViewPagerTransformers are native, so you don't need to use a library. Just create a class, implement the PageTransformer interface and override the method transformPage.
In your layout xml define a tablayout and a FrameLayout like this:
..................your xml code...............
.............................................................
<com.google.android.material.tabs.TabLayout
android:id="#+id/simpleTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimary"
app:tabIndicatorColor="#0080FF"
app:tabSelectedTextColor="#050505"
app:tabTextColor="#color/colorAccent">
<com.google.android.material.tabs.TabItem
android:id="#+id/abcd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Item 1" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item 2" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item 3" />
</com.google.android.material.tabs.TabLayout>
<FrameLayout
android:id="#+id/simpleFrameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This layout is defined for three tabs. You can make it for more tabs by adding more tabs if you like.
Then define the fragments for each tab. In this case:
item_one_fragment:
<?xml version="1.0" encoding="utf-8"?>
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="your.activity.context">
......................................
............................................
fragments xml
.............................
,.....................................
</RelativeLayout>
Similarly item 2 and item 3 fragment layouts.
Then define the fragments in java:
public class FirstItemFragment extends Fragment {
public ListView CallListView;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.item_one_fragment, container, false);
// Inflate the layout for this fragment
return view;
}
}
Simiarly second and third fragment.
Then in your Main Activity:
FrameLayout simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
TabLayout tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, new FirstItemFragment());
ft.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstItemFragment();
break;
case 1:
fragment = new SecondItemFragment();
break;
case 2:
fragment = new ThirdItemFragment();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.simpleFrameLayout, fragment)
.addToBackStack(null)
//Commit the transaction.
.commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Now when you run your activity you will have three tabs and when you click on any one you will go to the respective fragment without any swipe
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.
I have 2 questions. First, can me say someone, why this not works? I just try to change the fragment, but he does nothing. I just see the first fragment.
mainActivity:
...
if (savedInstanceState == null) {
fm.beginTransaction()
.add(R.id.firstFragment, new firstFragment()).commit();
}
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switchFragment(R.id.firstFragment, new firstFragment());
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switchFragment(R.id.secondFragment, new secondFragment());
}
});
}
private void switchFragment(int fragId, Fragment frag){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(fragId, frag);
ft.commit();
}
Fragments like this in the main.xml:
<Fragment
android:id="#+id/firstFragment"
android:name="com.example.firstFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/View01"
android:layout_below="#+id/view1" />
Fragmentclass just have this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_clublist, container, false);
return view;
}
And a Fragment just look like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFF0000"/>
I don't know, why he does not change the fragment. A check, that switchFragment really calling is true.
Second question is: Is this a good way to change fragments? What is, if i have 10 fragments?
Thanks for your help! :)
int fragId
should be the id of the container that hosts the Fragment, not the id of the fragment itself
So I want to have 3 buttons that always appear throughout fragments. I've got an activity with 3 buttons and a fragment layout that contains a fragment with actionbarsherlock inside. The problem is, the buttons in the activity are not clickable and nothing can be executed in the OnClickListener; but the buttons run just fine if I replace the fragment containing actionbarsherlock with a regular fragment without actionbarsherlock inside. I wonder what's wrong.
Here is my code.
activity_main.xml:
<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="2dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/button1" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/fragment_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:text="mission" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_centerHorizontal="true"
android:text="feed" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button2"
android:layout_alignBottom="#+id/button2"
android:layout_alignRight="#+id/fragment_content"
android:text="Profile" />
</RelativeLayout>
MyActivity.java:
public class MyActivity extends SherlockFragmentActivity {
/**
* Called when the activity is first created.
*/
Fragment frg;
ActionBarFragment b;
Button btnmission;
Button btnfeed;
Button btnprofile;
boolean small;
static int previousItem;
int tabname;
private Fragment mVisible = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
previousItem=1;
btnmission = (Button) findViewById(R.id.button1);
btnfeed = (Button) findViewById(R.id.button2);
btnprofile = (Button) findViewById(R.id.button3);
btnmission.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("clicked", "button");
if(previousItem!=1){
Intent intent=new Intent(getBaseContext(),MyActivity.class);
startActivity(intent);
}
previousItem=1;
}
});
btnfeed.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(previousItem!=2){
Intent intent=new Intent(getBaseContext(),MissionFragment.class);
intent.putExtra("class", "Feed");
startActivity(intent);
}
previousItem=2;
}
});
btnprofile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
private void setupFragments() {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
frg = (ActionBarFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_content);
if (frg == null) {
frg = new ActionBarFragment();
ft.add(R.id.fragment_content, frg);
}
ft.hide(frg);
ft.commit();
}
private void showFragment(Fragment fragmentIn) {
if (fragmentIn == null) return;
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (mVisible != null) ft.hide(mVisible);
ft.show(fragmentIn).commit();
mVisible = fragmentIn;
}
It adds a fragment to the activity and actionbar inside the fragment.
ActionBarFragment.java:
public class ActionBarFragment extends SherlockFragment {
int tabname;
#Override
public void onStart()
{
// TODO Auto-generated method stub
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.empty_view, container, false);
// Getting an instance of action bar
ActionBar actionBar = this.getSherlockActivity().getSupportActionBar();
// Enabling Tab Navigation mode for this action bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Enabling Title
actionBar.setDisplayShowTitleEnabled(true);
// Creating Android Tab
Tab tab1 = actionBar.newTab()
.setText("Nova Missoes")
.setTabListener(new CustomTabListener<ListMission>(this.getSherlockActivity(), "mission list", ListMission.class));
// Adding Android Tab to action bar
actionBar.addTab(tab1);
// Creating Apple Tab
Tab tab2 = actionBar.newTab()
.setText("Missoes Concluidas")
.setTabListener(new CustomTabListener<MissionAccomplished>(this.getSherlockActivity(), "mission accomplished", MissionAccomplished.class));
// Adding Apple Tab to action bar
actionBar.addTab(tab2);
Intent in=getSherlockActivity().getIntent();
tabname=in.getIntExtra("tabname", 0);
Log.i("intent", Integer.toString(tabname));
if(tabname==2){
actionBar.selectTab(tab2);
}
// Orientation Change Occurred
if(savedInstanceState!=null){
int currentTabIndex = savedInstanceState.getInt("tab_index");
actionBar.setSelectedNavigationItem(currentTabIndex);
}
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
int currentTabIndex = getSherlockActivity().getSupportActionBar().getSelectedNavigationIndex();
outState.putInt("tab_index", currentTabIndex);
super.onSaveInstanceState(outState);
}
}
No problem with displaying the buttons and the tabs, it's just that the OnClickListener is not called when the program runs.