OnclickListner for fragement and activity in android - android

Hi I have a scenario like I have a created a Main Activity and different fragments. MainActivity I am implemented the bottom navigation bar it contains different tabs
1.Task
2.Account
3.Contact
For the above have created the different fragments above tabs we have a common button called '+'.
Now My problem is that if i opened the account fragment want to display the fragment details .In that account tab has common '+' button for all .If I click on + button want to create a new account fragment.
How to resolve it.
MainActivity:
public void initBottomNavigationItems() {
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.task:
toolbar.setTitle("Task");
fragment = new TaskFragement();
loadFragment(fragment);
return true;
case R.id.account:
toolbar.setTitle("Account");
fragment = new AccountFragement();
loadFragment(fragment);
return true;
case R.id.contact:
toolbar.setTitle("Contact");
fragment = new ContactFragment();
loadFragment(fragment);
return true;
case R.id.opportunity:
toolbar.setTitle("Opportunity");
fragment = new OpportuntityFragement();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
If click on account tab it will move to the account fragment .In the same way want if i click on fab button want to replace account fragment with create fragment .But my fab button is in activity_main not in account fragement.
AccountFragement:
public class AccountFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_account, container, false);
}
}
fragment_account.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:background="#color/White">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/slivergray"
app:cardCornerRadius="8dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/White">
<ImageView
android:id="#+id/appImage"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginLeft="16dp"
android:background="#drawable/ic_account_circle_black_24dp"
android:backgroundTint="#color/gray"
android:scaleType="centerCrop"
tools:ignore="ContentDescription"/>
<TextView
android:id="#+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/appImage"
android:paddingLeft="16sp"
android:paddingRight="16dp"
android:text="Apollo Hospital"
android:textColor="#color/black"
android:textSize="18sp"
tools:ignore="RtlHardcoded"/>
<TextView
android:id="#+id/subHeaderText"
style="#style/Base.TextAppearance.AppCompat.Subhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/headingText"
android:layout_toRightOf="#+id/appImage"
android:paddingLeft="16dp"
android:text="Hospital"
android:paddingRight="16dp"
android:textColor="#color/gray"
android:textSize="15sp"/>
<TextView
android:id="#+id/subHeadingText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/subHeaderText"
android:layout_toRightOf="#+id/appImage"
android:gravity="left"
android:lines="5"
android:maxLines="5"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:text="stories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detail"
android:textColor="#color/gray"
android:textSize="14sp"/>
<TextView
android:id="#+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="⋮"
android:textColor="#color/gray"
android:layout_marginRight="10dp"
android:textAppearance="?android:textAppearanceLarge"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/subHeadingText">
<LinearLayout
android:layout_width="209dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="30dp"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:backgroundTint="#color/gray"
android:src="#drawable/ic_account_circle_black_24dp"></ImageView>
<Button
android:id="#+id/action1"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Action 1"
android:textColor="#color/gray"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="right">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:src="#drawable/ic_account_circle_black_24dp"
android:layout_marginLeft="50dp"></ImageView>
<Button
android:id="#+id/action2"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Action 2"
android:textColor="#color/gray"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</RelativeLayout>

I understand that you want to call your activity method from fragment.(from a + button in fragment).
Then you can use an interface in your fragment to get callback in activity.
public class AccountFragment extends Fragment {
OnFabClickListener listener;
// Container Activity must implement this interface
public interface OnFabClickListener{
public void onCreateNewAccount();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener= (OnFabClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFabClickListener");
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onCreateNewAccount();
}
});
}
...
}
Then in your activity implement the interface this way.
public class MainActivity extends AppCompatActivity implements OnFabClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
}
#Override
public void onCreateNewAccount() {
//Add your new account creation code here like loadFragment
}
}

Related

call another java activity from fragment class

Hey i have a simple question. i have a mobile_navigation that contain code to call a fragment class, and i have the fragment class but i want to call / pass to another java class. for example i have Inputdata.xml that when tap will go to fragment class nah i want when i tap the input xml it will instantly go to another java class not stuck in fragment class
here is the example code for mobile_navigation
<fragment
android:id="#+id/nav_pantuan"
android:name="com.joshua.r0th.crud2.ui.gallery.GalleryFragment"
android:label="#string/pantauan"
tools:layout="#layout/fragment_pantauan" />
and here is the GalleryFragment code
public class GalleryFragment extends Fragment {
private GalleryViewModel GalleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
GalleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_pantauan, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
GalleryViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
and this is the another java class that i willing to reach
public class pantauan extends AppCompatActivity {
database1 myDb;
EditText editNomorRumah,editJentikDalam,editJentikLuar;
Button btnAddData;
Button btnViewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pantauan);
myDb = new database1(this);
editNomorRumah = (EditText)findViewById(R.id.nomorrmh);
editJentikDalam = (EditText)findViewById(R.id.jentikdirumah);
editJentikLuar = (EditText)findViewById(R.id.jentikdiluarrumah);
btnAddData = (Button)findViewById(R.id.tambahdata);
btnViewAll = (Button)findViewById(R.id.lihatdata);
AddData();
viewAll();
}
//fungsi tambah
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editNomorRumah.getText().toString(),
editJentikDalam.getText().toString(),
editJentikLuar.getText().toString() );
if(isInserted == true)
Toast.makeText(pantauan.this,"Data Iserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(pantauan.this,"Data Not Iserted",Toast.LENGTH_LONG).show();
}
}
);
}
//fungsi menampilkan data
public void viewAll() {
btnViewAll.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Noting Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext() ) {
buffer.append("NomorRumah :"+ res.getString(0)+"\n");
buffer.append("JentikDalam :"+ res.getString(1)+"\n");
buffer.append("JentikLuar :"+ res.getString(2)+"\n");
}
// show all data
showMessage("Data",buffer.toString());
}
}
);
}
//membuat alert dialog
public void showMessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
and here is the Input.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/gradient"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="70dp"
android:background="#drawable/gradient"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="30dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Nomor Rumah" />
<EditText
android:id="#+id/nomorrmh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/roundtext" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Jentik Di Dalam Rumah" />
<EditText
android:id="#+id/jentikdirumah"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/roundtext" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Jentik Di Luar Rumah" />
<EditText
android:id="#+id/jentikdiluarrumah"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/roundtext"
android:layout_marginBottom="10dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_gravity="center">
<Button
android:id="#+id/tambahdata"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:background="#d67601"
android:text="Tambah Data"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
<Button
android:id="#+id/lihatdata"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:background="#d67601"
android:text="contoh lihat data"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<TextView
android:id="#+id/textviewadd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="26dp"
android:gravity="center_horizontal"
android:text="Input Data"
android:textColor="#fff"
android:textSize="26sp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/text_gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
My goal is to pass the fragment into the java class that i want, because i dont know how to put that input class to the fragment always get cannot be cast to androidx.fragment.app.Fragment when i replace the GalleryFragment with pantauan.java code. thank you

Fragment over listview activity [duplicate]

This question already has answers here:
Fragment won't launch
(2 answers)
Closed 5 years ago.
I am pretty new to android development, so please don't flame me for stupid questions/mistakes!
I have a listview inside my activity, but i want to open up a fragment when a frame in the listview is clicked on. I have the onclick working, but it is not launching the new activity.
I'll include my code below.
This is the oncreate
protected void onCreate (Bundle savedInstanceState)
{
//Fragment fragment_blank2=new SomeFragment();
e = myBadData.getData();
super.onCreate(savedInstanceState);
setContentView(R.layout.event_list);
events=(ListView) findViewById(R.id.dayList);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);
events.setAdapter(adapter);
events.setOnItemClickListener(this);
}
this is the onclick
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
myBadData.setId(i);
Fragment fr = new event_description();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.eventdescription, fr);
}
this is the XML of the fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id = "#+id/eventdescription"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="137dp"
android:text="#string/event_name"
android:textSize="26sp"
android:layout_gravity="top"
android:gravity="top|center"
android:paddingTop="10dp"
android:id="#+id/textView"
android:background="#android:color/holo_orange_light"
android:textColor="#android:color/black"
android:layout_weight="1.08" />
<TextView
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:layout_marginTop="#dimen/activity_top_margin"
android:layout_marginLeft="#dimen/activity_side_margin"
android:textSize="18sp"
android:drawableTint="#android:color/background_dark" />
<TextView
android:text="#string/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/time"
android:layout_marginTop="70dp"
android:layout_marginLeft="#dimen/activity_side_margin"
android:textSize="18sp" />
<TextView
android:text="#string/cost"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cost"
android:layout_marginTop="#dimen/activity_top_margin"
android:layout_marginRight="70dp"
android:textSize="18sp"/>
<TextView
android:text="#string/address"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/address"
android:layout_marginTop="70dp"
android:layout_marginRight="60dp"
android:textSize="18sp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="135dp"
android:layout_marginLeft="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:id="#+id/tv_long"
android:paddingTop="10dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/sample_text"
android:textSize="18sp"
android:layout_weight="1.08">
</TextView>
</LinearLayout>
</ScrollView>
<Button
android:text="#string/add_to_calendar"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/button2"
android:layout_gravity="center_horizontal"
android:layout_marginTop="95dp"/>
</FrameLayout>
here is the class of the fragment
public class event_description extends Fragment
{
#Nullable
//#Override
public View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate (R.layout.event_description, container, false);
Bundle args = getArguments();
String arg = args.getString(eventList.KEY_NAME);
//return super.(R.layout.event_description, container, false);
return view;
}
public View getView() {
return getView();
}
}
For Your Activity XML
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/my_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/dayList"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</FrameLayout>
And Pass Activity's Container in FramgmentTransaction
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
myBadData.setId(i);
Fragment fr = new event_description();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
//Your Container of Activity
fragmentTransaction.add(R.id.my_frame, fr);
fragmentTransaction.commit();
}
and Don't forgot to commint it.
No need to use framgment's FrameLayout as a container..

App crashes when switching between Sliding Tabs by clicking the tabs (not swiping)

So I'm using PagerSlidingTabStrip. I implemented it just like it was suggested in the tutorial and followed the sample/demo-app code.
I have 3 tabs: Calculator | Percentage | History
All 3 extend Fragment. I can swipe between these tabs no problem. But I get a NullPointerException is when I'm on the Calculator tab trying to click the History tab. Here's the error I'm getting:
java.lang.NullPointerException
at sleeping_vityaz.onerm.tabsswipe.HistoryFragment.loadScreen(HistoryFragment.java:69)
at sleeping_vityaz.onerm.tabsswipe.HistoryFragment.setUserVisibleHint(HistoryFragment.java:57)
at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:555)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:514)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:495)
at com.astuetz.PagerSlidingTabStrip$2.onClick(PagerSlidingTabStrip.java:299)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Here is my HistoryFragment code:
public class HistoryFragment extends Fragment {
public RecordArrayAdapter adapter;
ArraySwipeAdapterSample mAdapter;
View rootView;
DBTools dbTools = null;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.history_layout, container, false);
loadScreen();
return rootView;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
loadScreen();
} else {
Log.d("MyFragment", "Fragment is not visible.");
}
}
private void loadScreen() {
dbTools = DBTools.getInstance(this.getActivity());
final List<RecordObject> recordsList = dbTools.getAllRecords();
if (recordsList.size() != 0) {
ListView listView = (ListView) rootView.findViewById(R.id.records_list);
mAdapter = new ArraySwipeAdapterSample<String>(getActivity(), R.layout.record_entry, R.id.key_id, recordsList);
listView.setAdapter(mAdapter);
mAdapter.setMode(SwipeItemMangerImpl.Mode.Single);
SwipeLayout swipeLayout = (SwipeLayout) getActivity().findViewById(R.id.swipe);
/*adapter = new RecordArrayAdapter(this.getActivity(), recordsList);
listView.setAdapter(adapter);*/
}
}
}
history_layout.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/records_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"></ListView>
record_entry.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp">
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="80dp">
<!-- Bottom View Start-->
<LinearLayout
android:id="#+id/bottom_wrapper"
android:layout_width="80dp"
android:layout_height="match_parent"
android:background="#66ddff00"
android:weightSum="1">
<ImageView
android:id="#+id/img_trash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/accent"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:src="#drawable/ic_action_delete" />
<!--What you want to show-->
</LinearLayout>
<!-- Bottom View End-->
<!-- Surface View Start -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:padding="10dp">
<!--What you want to show in SurfaceView-->
<TextView
android:id="#+id/key_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/onerm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="2.2"
android:gravity="center_vertical"
android:text="WEIGHT"
android:textColor="#444444"
android:textSize="16sp"
android:layout_marginLeft="4dp" />
<TableLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="3">
<TextView
android:id="#+id/weight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="WEIGHT"
android:textColor="#444444"
android:textSize="12sp" />
<TextView
android:id="#+id/reps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REPS"
android:textColor="#444444"
android:textSize="12sp" />
</TableLayout>
<TextView
android:id="#+id/date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|right"
android:layout_weight="2"
android:text="DATE"
android:textColor="#444444"
android:textSize="12sp"
android:gravity="center_vertical|right" />
</LinearLayout>
<!-- Surface View End -->
</com.daimajia.swipe.SwipeLayout>
</LinearLayout>
TabsAdapter.java
public class TabsAdapter extends FragmentPagerAdapter {
final private int NUM_TABS = 3;
public TabsAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: return new CalculatorFragment();
case 1: return new PercentageFragment();
case 2: return new HistoryFragment();
}
return null;
}
#Override
public int getCount() {
return NUM_TABS;
}
#Override
public CharSequence getPageTitle (int position) {
switch (position) {
case 0: return "Calculator";
case 1: return "Percentage";
case 2: return "History";
default:return null;
}
}
}
What could be causing this error? This only happens when I try to switch from the Calculator fragment to History fragment by clicking the tabs (and not swiping) AND when the user has already saved something to the database (recordsList.size() != 0). If recordsList is empty, there's no error.
Also, HistoryFragment.java:68 is the following line
ListView listView = (ListView) rootView.findViewById(R.id.records_list);
I was able to solve this by myself :) So what happened was that setUserVisibleHint method was calling loadScreen because the screen was visible to the user. The problem with that was that History fragment's onCreateView was never called in the first place! So all I had to do was to check for rootView!=null in my loadScreen method. Duh! This fixed everything.
This is what I had before
if (recordsList.size() != 0) {
and what I have now
if (recordsList.size() != 0 && rootView!=null) {
Set in fragment where you goto crash:
if (activity != null && isAdded) {
// perform your task
}

Change a particuar view in Fragment

I am new to android developing and I am currently stumped at this situation.
Is there a way to change a particular child view of a fragment?
For example, I have a TextView and Button in a Fragment. Now after inflating this fragment and committing it, I would like to only change the text of the TextView based on the user input.
EDIT: The same layout is used to create multiple fragments. I would like to just change the TextView of a particular Fragment.
MainActivity Code:
public class MainActivity extends Activity {
Button bt;
EditText et;
LinearLayout ly;
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.badd);
ly=(LinearLayout) findViewById(R.id.lay_ver);
et=(EditText) findViewById(R.id.etadd);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// multiple fragments are created
MyFragment f=new MyFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction t=fm.beginTransaction();
t.add(R.id.sv1, f, "hi");
t.commit();
et.setText("");
}
});
//would like to change the text of the textview of the fragment
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Fragment Code:
public class MyFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.frag_lay, null);
return v;
}
}
activity_main XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lay_ver"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/lay_hor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/etadd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="80"
android:hint="Enter Subject"
android:paddingTop="20dp" />
<Button
android:id="#+id/badd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="Add" />
</LinearLayout>
<ScrollView
android:id="#+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/sv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layfrag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.53"
android:text="HiHow"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
You can add a list of Fragments in your activity and each fragment to the list when you create them. Then you can get the fragment you want to change and do as cdblades said :
View parent = fragment.getView();
View childTextView = (TextView)parent.findViewById(R.id.myChildTextView);
But why are you adding the fragments in the same container?
The base View class has the findById() method that you can use to get a reference to child views like so:
View parent = fragment.getView();
View childTextView = (TextView)parent.findViewById(R.id.myChildTextView);

Fragment UI components null TextViews

New android developer here. I am trying to create a dynamic UI that loads based on the users selection of a RadioGroup. Based on their selection, one of 3 possible fragments will be loaded into a LinearLayout section. This is my first attempt at my own sample problem that is not just a walk-through tutorial. Here is the main activity:
public class BaseConverter extends Activity {
RadioGroup convert;
Fragment toFragment;
RadioGroup toRadioGroup = null;
TextView inputDisplay = null;
TextView outputDisplay = null;
TextView resultTitle = null;
#Override
public void onCreate(Bundle sIS) {
super.onCreate(sIS);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.base_converter);
convert = (RadioGroup) this.findViewById(R.id.bc_convert_group);
convert.setOnCheckedChangeListener(new ConvertListener());
FragmentManager fm = getFragmentManager();
FragmentTransaction converterFragment = fm.beginTransaction();
ConvertEmptyFragment emptyTo = new ConvertEmptyFragment();
converterFragment.replace(R.id.bc_converter_fragment, emptyTo);
converterFragment.commit();
FragmentTransaction toFragment = fm.beginTransaction();
ConvertEmptyFragment emptyConverter = new ConvertEmptyFragment();
toFragment.replace(R.id.bc_to_fragment, emptyConverter);
toFragment.commit();
}
#Override
public void onResume() {
convert.clearCheck();
super.onResume();
}
#Override
public void onPause() {
convert.clearCheck();
super.onPause();
}
// I put a little null check so you can see how I'm trying to access the TextViews and what results
public void updateUIComponents(){
View converterView = this.findViewById(R.id.bc_converter_fragment);
inputDisplay = (TextView)converterView.findViewById(R.id.bc_display_input);
outputDisplay = (TextView)converterView.findViewById(R.id.bc_display_output);
if (inputDisplay == null){
Log.d("BaseConverter", "inputDisplay == null");
} else {
Log.d("BaseConverter", "inputDisplay != null");
}
}
class ConvertListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Fragment toFragment;
Fragment converterFragment;
switch (checkedId) {
case R.id.bc_convert_binary:
toFragment = new ConvertRBFragmentBinary();
converterFragment = new ConverterFragmentBinary();
break;
case R.id.bc_convert_decimal:
toFragment = new ConvertRBFragmentDecimal();
converterFragment = new ConverterFragmentDecimal();
break;
case R.id.bc_convert_hex:
toFragment = new ConvertRBFragmentHex();
converterFragment = new ConverterFragmentHex();
break;
default:
toFragment = new ConvertEmptyFragment();
converterFragment = new ConvertEmptyFragment();
break;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction converterTransaction = fm.beginTransaction();
converterTransaction.replace(R.id.bc_converter_fragment, converterFragment);
converterTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
converterTransaction.commit();
FragmentTransaction toTransaction = fm.beginTransaction();
toTransaction.replace(R.id.bc_to_fragment, toFragment);
toTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
toTransaction.commit();
updateUIComponents();
}
}
So, based on what a user chooses, the proper fragments will be loaded into the respective LinearLayout sections. However, now I want to implement the business logic of the fragments (which is just integer base conversion; i.e. binary number to decimal...) but when I try to access the TextViews, as seen in the updateUIComponents method, I get null pointers. What am I missing?
Here's the ConverterFragmentBinary class for reference:
public class ConverterFragmentBinary extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sIS){
View v = inflater.inflate(R.layout.converter_fragment_binary, container, false);
return v;
}
}
and its respective xml layout for reference:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/bc_binary_converter_logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:maxHeight="30dip"
android:src="#drawable/binary_converter" />
<TextView
android:id="#+id/bc_display_input"
style="#style/input_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical|right"
android:lines="1"
android:minHeight="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF000000"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/button_num_0"
style="#style/op_button_land"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:gravity="center"
android:onClick="num0"
android:text="#string/num_0" />
<Button
android:id="#+id/button_num_1"
style="#style/op_button_land"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:gravity="center"
android:onClick="num1"
android:text="#string/num_1" />
</LinearLayout>
<TextView
android:id="#+id/bc_result_title"
style="#style/radio_button_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_marginTop="10dip"
android:gravity="left"
android:text="#string/choose_convert" />
<TextView
android:id="#+id/bc_display_output"
style="#style/display_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical|right"
android:lines="1"
android:minHeight="30sp" />
</LinearLayout>
and then heres the main activity it gets loaded into:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/base_conversion_layout"
style="#style/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="5"
android:baselineAligned="false"
android:gravity="center_vertical|left"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="vertical" >
<TextView
style="#style/radio_button_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convert" />
<RadioGroup
android:id="#+id/bc_convert_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dip" >
<RadioButton
android:id="#+id/bc_convert_binary"
style="#style/radio_button"
android:text="#string/binary" />
<RadioButton
android:id="#+id/bc_convert_decimal"
style="#style/radio_button"
android:text="#string/decimal" />
<RadioButton
android:id="#+id/bc_convert_hex"
style="#style/radio_button"
android:text="#string/hex" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="#+id/bc_to_fragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/bc_converter_fragment"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="13"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
Thanks in advance and sorry for the long code blocks but I figured it was better to include more than less.
Also, you should inflate your Fragments layout to bring it from your XML to your Java code instead of simply referring it using findViewById() method.
So instead of doing this,
View converterView = this.findViewById(R.id.bc_converter_fragment);
Do this inside your onCreateView method of the fragment,
View converterView = infalter.inflate(R.id.bc_converter_fragment,null);
updateUIComponents(converterView);//call this methid and pass your view
new method looks like this,
public void updateUIComponents(View converterView){
inputDisplay = (TextView)converterView.findViewById(R.id.bc_display_input);
outputDisplay = (TextView)converterView.findViewById(R.id.bc_display_output);
if (inputDisplay == null){
Log.d("BaseConverter", "inputDisplay == null");
} else {
Log.d("BaseConverter", "inputDisplay != null");
}
}

Categories

Resources