How use OnClickListener in Fragments - java

This is my code. I'm still learning android studio. I want to show a toast when the button is clicked but when I run the application and click the button it does nothing. (this is a Fragment). Does anyone know how to fix this? I tried putting "onClick" method in the xml(android:onClick="onClick") then the app crashed as soon as I clicked the button.
fragment_fragment_course.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".fragmentCourse">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Course"
android:textSize="25sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnCourse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/textView2"
app:layout_constraintStart_toStartOf="#+id/textView2"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragmentCourse.java
package com.example.sma;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
public class fragmentCourse extends Fragment implements View.OnClickListener {
Button btn2;
public fragmentCourse() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View CView = inflater.inflate(R.layout.fragment_fragment_course, container, false);
btn2 = (Button)CView.findViewById(R.id.btnCourse);
final TextView txt = (TextView)CView.findViewById(R.id.textView2);
btn2.setOnClickListener(this);
return CView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCourse:
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
break;
}
}
}

Override onViewCreated method and move below code to there. You can't access the views in onCreateView of fragment.
btn2 = (Button)CView.findViewById(R.id.btnCourse);
final TextView txt = (TextView)CView.findViewById(R.id.textView2);
btn2.setOnClickListener(this)

Related

Unable to change background color of a fragment

I am new to android and currently learning right now.
I faced a problem related to android-fragments, I write code and it did nothing! Just show the fragment color.
when I tried to remove the color of the fragment, it worked! I am unable to rectify this problem. Please help!
XML -activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="113dp"
android:layout_height="50dp"
android:text="Switch1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
<fragment
android:id="#+id/fragment"
android:name="com.example.fragments.Color_Purple"
android:layout_width="390dp"
android:layout_height="385dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.68"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137" />
</androidx.constraintlayout.widget.ConstraintLayout>
XML - Fragment code
<?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=".Color_Purple">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C403FA" />
</FrameLayout>
JAVA-mainActivity.java
package com.example.fragments;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1;
Fragment f1;
Boolean flag=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
f1=new Color_Purple();
// Toast.makeText(getApplicationContext(),"Button pressed",Toast.LENGTH_SHORT).show();
FragmentManager fm=getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
if(flag)
{
findViewById(R.id.fragment).setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(),"Button pressed Color GREEN",Toast.LENGTH_SHORT).show();
flag=false;
}
else
{
findViewById(R.id.fragment).setBackgroundColor(Color.RED);
//Toast.makeText(getApplicationContext(),"Button pressed Color RED",Toast.LENGTH_SHORT).show();
flag=true;
}
}
});
}
}
Java - fragment java code
package com.example.fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Color_Purple extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_color__purple, container, false);
}
}
Note:
If i remove android:background from xml - fragment, this code works but not with color.
just change :
Boolean flag = true;
to
boolean flag = true;
and remove android:background="#C403FA" from your TextView :
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C403FA" //remove this line
/>

Layout issue with Viewpages in Android

i work with viewpages i have 3 and i got this in every page.
i dont find the error to get this output]2
there ist a white stripe at the top and buttom. i dont find anything to fix it. here is my code:
and the story.java:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class Story1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_story1, container, false);
Button _play = (Button) rootView.findViewById(R.id.btn_play);
_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return rootView;
}
}
the main layout:
<?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="com.jeravare.hypralyne.MainActivity">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="8dp"></android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
The problem is not in the fragment layout.
You can change this:
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginTop="8dp"
to this:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="8dp" // you can remove this if you don't need a space at the top

BottomSheetDialogFragment setting peek hight and other behaviors

I want the bottom screen to peek and then take up the full screen when slid up. currently, I have it showing when I press "Button 1" because I cannot get the peek to work.
I can, however, slide it up so that it takes up the full screen. Ideally, it would do this automatically.
When I slide it back down, it goes down all the way.
I want the following behavior:
The Bottom Sheet should peek 300dp or whatever, at all times.
Sliding up on the Bottom Sheet should result in it taking up the full screen view, like in the second picture.
Sliding down the Bottom Sheet should go back to its peek height.
I don't know how to control the Bottom Sheet behavior because, the BottomSheetBehaviorclass only seems to work for the ones defined in XML.
activity_main.xml
<android.support.design.widget.CoordinatorLayout
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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp">
<Button
android:id="#+id/button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:padding="16dp"
android:layout_margin="8dp"
android:textColor="#android:color/white"
android:background="#android:color/holo_green_dark"/>
// ...
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
fragment_bottom_sheet.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="true"
android:background="#android:color/holo_orange_light"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Some text..."
android:padding="16dp"
android:textSize="16sp"/>
</RelativeLayout>
MainActivity.java
package com.example.qqq.bottomsheets;
import android.os.Bundle;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private BottomSheetBehavior mBottomSheetBehavior;
private TestBottomSheetDialogFragment mTestBottomSheetDialogFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById( R.id.button_1 );
Button button2 = (Button) findViewById( R.id.button_2 );
Button button3 = (Button) findViewById( R.id.button_3 );
mTestBottomSheetDialogFragment = new TestBottomSheetDialogFragment();
button1.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_1: {
mTestBottomSheetDialogFragment.show(getSupportFragmentManager(), mTestBottomSheetDialogFragment.getTag());
break;
}
}
}
}
TestBottomSheetDialogFragment.java
package com.example.qqq.bottomsheets;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TestBottomSheetDialogFragment extends BottomSheetDialogFragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return super.onCreateDialog(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bottom_sheet, container, false);
return view;
}
}

BottomBar fragments in Android studio

How can I add fragments for each tab in BottomBar in Android studio please a good example like list view or grid view for each tab..thanks
You need to implement SetOnTabSelectListerner.
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(#IdRes int tabId) {
Fragment fragment = null;
Class fragmentClass = null;
switch (tabId) {
case R.id.tab_one:
fragmentClass = TabOneFragment.class;
break;
case R.id.tab_two:
fragmentClass = TabTwoFragment.class;
break;
case R.id.tab_three:
fragmentClass = TabThreeFragment.class;
break;
case R.id.tab_four:
fragmentClass = TabFourFragment.class;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
});
main_activity.java
import android.app.Activity;
import android.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements communicator{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(int i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 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"
android:background="#00BBFF"
android:orientation="vertical"
tools:context="com.example.dhanya.myfragmentexample.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentexample.FragmentA"
/>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentexample.FragmentB"
/>
</android.widget.LinearLayout>
fragmentA.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{
ListView list;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
list=(ListView)getActivity().findViewById(R.id.lv);
ArrayAdapter ad=ArrayAdapter.createFromResource(getActivity(),R.array.listval,android.R.layout.simple_list_item_1);
list.setAdapter(ad);
list.setOnItemClickListener(this);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt=(TextView)view;
String str=txt.getText().toString();
comm.respond(position);
}
}
fragmentA.xml
<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="com.example.dhanya.myfragmentexample.FragmentA"
android:background="#FFBB00">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv"/>
</FrameLayout>
fragmentB.java
package com.example.dhanya.myfragmentexample;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.textv);
}
public void changedata(int i)
{
Resources res=getResources();
String[] des=res.getStringArray(R.array.desciptions);
// String str=Integer.toString(i);
txt.setText(des[i]);
// txt.setText(str); }}
fragmentB.xml
<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="com.example.dhanya.myfragmentexample.FragmentB"
android:background="#99CC00"
>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textv"/>
</FrameLayout>
strings.xml
<resources>
<string name="app_name">MyFragmentExample</string>
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
<string-array name="listval">
<item>fragments</item>
<item>Activities</item>
<item>Services</item>
<item>Content Providers</item>
</string-array>
<string-array name="desciptions">
<item>A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).</item>
<item>Activities are one of the fundamental building blocks of apps on the Android platform. They serve as the entry point for a user's interaction with an app, and are also central to how a user navigates within an app (as with the Back button) or between apps (as with the Recents button). </item>
<item>A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.</item>
<item>Content providers can help an application manage access to data stored by itself, stored by other apps, and provide a way to share data with other apps. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Implementing a content provider has many advantages. </item>
</string-array>
</resources>
communicator.java
public interface communicator {
public void respond(int i);
}
//Grid view
main_activity.xml
<ScrollView xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="#+id/gridview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="50dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>
</ScrollView>
mainactivity.java
package com.example.harish.mylayoutexamples;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class GridActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
GridView gridView;
static final String[] numbers = new String[] {
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridView = (GridView) findViewById(R.id.gridview1);
// Create adapter to set value for grid view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
/* gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) v).getText() , Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText() , Toast.LENGTH_SHORT).show();
}
}
fragments dynamic loading
Main activity. Java
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button firstFragment, secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of Button's
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = (Button) findViewById(R.id.secondFragment);
// perform setOnClickListener event on First Button
firstFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load First Fragment
loadFragment(new FirstFragment());
}
});
// perform setOnClickListener event on Second Button
secondFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// load Second Fragment
loadFragment(new SecondFragment());
}
});
}
private void loadFragment(Fragment fragment) {
// create a FragmentManager
FragmentManager fm = getFragmentManager();
// android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frameLayout, fragment);
//fragmentTransaction.add(R.id.firstFragment,fragment);
fragmentTransaction.commit(); // save the changes
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MAIN_ACTIVTY.XML
<LinearLayout 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:orientation="vertical"
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=".MainActivity">
<!-- display two Button's and a FrameLayout to replace the Fragment's -->
<Button
android:id="#+id/firstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/button_background_color"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<Button
android:id="#+id/secondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#color/button_background_color"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp" />
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp" />
</LinearLayout>
FIRST_FRAGMENT.JAVA
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class FirstFragment extends Fragment {
View view;
Button firstButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_first, container, false);
// get the reference of Button
firstButton = (Button) view.findViewById(R.id.firstButton);
// perform setOnClickListener on first Button
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "First Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
FIRST_FRAGMENT>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"
tools:context="com.abhiandroid.fragmentexample.FirstFragment">
<!--TextView and Button displayed in First Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is First Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/firstButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="First Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
SECOND_FRAGMENT>JAVA
package com.abhiandroid.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class SecondFragment extends Fragment {
View view;
Button secondButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_second, container, false);
// get the reference of Button
secondButton = (Button) view.findViewById(R.id.secondButton);
// perform setOnClickListener on second Button
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// display a message by using a Toast
Toast.makeText(getActivity(), "Second Fragment", Toast.LENGTH_LONG).show();
}
});
return view;
}
}
SECOND_FRAGMENT>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"
tools:context="com.abhiandroid.fragmentexample.SecondFragment">
<!--TextView and Button displayed in Second Fragment -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:text="This is Second Fragment"
android:textColor="#color/black"
android:textSize="25sp" />
<Button
android:id="#+id/secondButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/green"
android:text="Second Fragment"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
main_activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void respond(String i) {
android.support.v4.app.FragmentManager fm=getSupportFragmentManager();
FragmentB f2= (FragmentB)fm.findFragmentById(R.id.fragment2);
f2.changedata(i);
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 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="com.example.dhanya.myfragmentcommsimple.MainActivity"
android:orientation="vertical">
<fragment
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/fragment"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentA">
</fragment>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment2"
android:name="com.example.dhanya.myfragmentcommsimple.FragmentB">
</fragment>
</android.widget.LinearLayout>
fragment_A.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
public class FragmentA extends Fragment implements View.OnClickListener{
int count=0;
Button bt;
communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm= (communicator) getActivity();
bt=(Button)getActivity().findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
count++;
comm.respond("The button is clicked "+ count+" times");
}
}
FRAGMET_A.xml
<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="com.example.dhanya.myfragmentcommsimple.FragmentA"
android:background="#99FF00">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn"
android:text="counter"
android:layout_margin="40dp"/>
</FrameLayout>
FRAGMENT_B.java
package com.example.dhanya.myfragmentcommsimple;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentB extends Fragment {
TextView txt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_b, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt=(TextView)getActivity().findViewById(R.id.tv);
}
public void changedata(String i)
{
txt.setText(i);
}
}
FRAGMENT_B.xml
<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="com.example.dhanya.myfragmentcommsimple.FragmentB"
android:background="#FFBB00">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="haiiii"
android:id="#+id/tv"
android:layout_margin="50dp"/>
</FrameLayout>
COMMUNICATOR.java
package com.example.dhanya.myfragmentcommsimple;
public interface communicator {
public void respond(String i);
}

Can anyone explain me how the execution process runs in this java code for Fragments in Android Studio [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I wrote this code according to the video tutorial found here
about Android Fragments, but I can't understand how the flow of execution runs through these codes. As in the tutorial I have made two fragments alone with the Main Activity. The whole program works fine, but I can't understand how the execution flow goes. Please be kind enough to explain me. Here are my source codes, I am
really sorry as they are too long, I posted all of my code. This is the Main Activity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements top_layout_fragment.TopSelectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//overiding the method from the interface
#Override
public void createMeme(String top, String bottom) {
bottom_layout_fragment bottomLayoutFragment = (bottom_layout_fragment) getSupportFragmentManager().findFragmentById(R.id.fragment2);
bottomLayoutFragment.setText(top, bottom);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the activity_main.xml
<?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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.kasun.fragments.top_layout_fragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/top_layout_fragment" />
<fragment
android:layout_width="320dp"
android:layout_height="320dp"
android:name="com.example.kasun.fragments.bottom_layout_fragment"
android:id="#+id/fragment2"
tools:layout="#layout/bottum_layout_fragment"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
this is the top_layout_fragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
import java.util.ServiceConfigurationError;
public class top_layout_fragment extends Fragment {
private static EditText firstText, secondText;
TopSelectionListener activityCommand;
public interface TopSelectionListener {
public void createMeme(String top, String bottom);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activityCommand = (TopSelectionListener) activity;
}
catch(ClassCastException e){
throw new ClassCastException (activity.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_layout_fragment, container, false);
firstText = (EditText) view.findViewById(R.id.firstText);
secondText = (EditText) view.findViewById(R.id.secondText);
final Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View view) {
activityCommand.createMeme(firstText.getText().toString(), secondText.getText().toString());
}
}
this is top_layout_fragment.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">
<EditText
android:id="#+id/firstText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320dp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="#+id/secondText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="320dp"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/firstText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#+id/secondText"
android:layout_marginTop="20dp"
android:text="#string/button_Texg"
android:id="#+id/button" />
</RelativeLayout>
this is the bottom_layout_fragment.java
package com.example.kasun.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
public class bottom_layout_fragment extends Fragment {
private TextView topText,bottomText;
// need to overide the onCreateViewMethod
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.bottum_layout_fragment,container,false);
topText=(TextView)view.findViewById(R.id.topText);
bottomText=(TextView)view.findViewById(R.id.bottomText);
return view;
}
public void setText(String topText,String bottomText){
this.topText.setText(topText);
this.bottomText.setText(bottomText);
}
}
this is the bottom_layout_fragment.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"
android:background="#drawable/image1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/topText"
android:layout_marginTop="34dp"
android:textColor="#FFF"
android:gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/bottomText"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/topText"
android:layout_alignStart="#+id/topText"
android:layout_marginBottom="35dp"
android:textColor="#FFF"
android:gravity="center_horizontal" />
</RelativeLayout>
This is set up so you have one activity displaying two fragments. You can see both fragments are included in the activities layout file.
The top fragment needs to communicate with the bottom one to update its text and does so through an interface called TopSelectionListener. You will notice that your activity implements that interface. The other important part is the top fragment keeps a reference to your activity using the interface. You can see that in the top fragment's onAttach method. The activity displaying this fragment must implement the TopSelectionListener interface or else you will get a ClassCastException and your application will crash.
activityCommand = (TopSelectionListener) activity;
When the button is clicked in the top fragment it will call activityCommand.createMeme(...) which calls the createMeme method in your activity.
The createMeme method then looks up a reference to your bottom Fragment and calls the setText method on it to update the text it shows.
There is another example how this works in the Android documentation.

Categories

Resources