Button in fragment could not be reached - android

I am new in android programming. Just trying to use fragment. I am using the following code :
public class SimpleFragActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_fragment);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_simple,
container, false);
Button btnClickMeBlue = (Button)rootView.findViewById(R.id.btnsimplefrag);
return rootView;
}
}
}
XML code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.framentexample.SimpleFragActivity$PlaceholderFragment" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:scale="centercrop"
android:src="#drawable/royal_enfield_blue" />
<Button
android:id="#+id/btnsimplefrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:text="Click Me Blue" />
</RelativeLayout>
but it throws an error saying
btnsimplefrag could not be resolved
Can anybody help me out? I tried many things and could not resolve the issue.

Related

Shared element back transition not working with recyclerview and cardviews in fragments

I'm trying to create a transition between a recycler view with cardviews fragment to a fragment that only contains 1 card. The problem is that the back transition is not working, while the enter transition is. If I remove setReorderingAllowed(true); then the back transition is working, but the enter transition stops working.
This is what I have.
Fragment with recyclerview with cardviews
public class OrdersFragment extends Fragment implements OrderAdapter.OnOrderListener {
private OrderAdapter mAdapter;
private TextView bonnenTextView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postponeEnterTransition();
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bonnen, container, false);
bonnenTextView = view.findViewById(R.id.bonnen_text_view);
RecyclerView orderRecyclerView = view.findViewById(R.id.order_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
orderRecyclerView.setLayoutManager(layoutManager);
if (mAdapter == null) {
mAdapter = new OrderAdapter(this);
fetchOrders();
}
orderRecyclerView.setAdapter(mAdapter);
return view;
}
private void fetchOrders() {
new OrderFetcher().fetch(new Callback() {
#Override
public void onComplete(Result result) {
if (result instanceof Result.Success) {
mAdapter.setOrders((Order[]) ((Result.Success<?>)result).data);
mAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getContext(), "Could not load orders", Toast.LENGTH_SHORT).show();
}
startPostponedEnterTransition();
}
});
}
#Override
public void onOrderClick(int position, View view, Order order) {
Log.i("OrderClick", "Transition name " + view.getTransitionName());
View carrierTextView = view.findViewById(R.id.carrier_text_view);
View numberTextView = view.findViewById(R.id.id_text_view);
View pickerTextView = view.findViewById(R.id.picker_text_view);
View locationTextView = view.findViewById(R.id.location_text_view);
FragmentTransaction transaction = getParentFragmentManager().beginTransaction();
transaction.addSharedElement(view, view.getTransitionName());
transaction.addSharedElement(carrierTextView, carrierTextView.getTransitionName());
transaction.addSharedElement(numberTextView, numberTextView.getTransitionName());
transaction.addSharedElement(pickerTextView, pickerTextView.getTransitionName());
transaction.addSharedElement(locationTextView, locationTextView.getTransitionName());
transaction.addSharedElement(bonnenTextView, bonnenTextView.getTransitionName());
transaction.replace(R.id.nav_host_fragment, BonFragment.newInstance(view.getTransitionName(), order));
transaction.addToBackStack(null);
transaction.setReorderingAllowed(true);
transaction.commit();
}
}
xml that goes with fragment above
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context=".ui.orders.OrdersFragment">
<TextView
android:id="#+id/bonnen_text_view"
android:transitionName="bonnen_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="#string/orders"
android:textColor="#color/secondary"
android:textSize="40sp"
android:textStyle="bold"
android:typeface="normal" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/order_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"/>
</LinearLayout>
Fragment with single cardview
public static BonFragment newInstance(String cardTransitionName, Order order) {
BonFragment bonFragment = new BonFragment();
Bundle args = new Bundle();
args.putParcelable("orderParcel", order);
args.putString("cardTransitionName", cardTransitionName);
bonFragment.setArguments(args);
return bonFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_bon, container, false);
CardView orderCard = root.findViewById(R.id.order_card);
TextView carrierTextView = root.findViewById(R.id.carrier_text_view);
TextView numberTextView = root.findViewById(R.id.id_text_view);
TextView pickerTextView = root.findViewById(R.id.picker_text_view);
TextView locationTextView = root.findViewById(R.id.location_text_view);
if (getArguments() != null && getArguments().getParcelable("orderParcel") != null) {
Order order = getArguments().getParcelable("orderParcel");
orderCard.setTransitionName(getArguments().getString("cardTransitionName"));
if (order != null) {
carrierTextView.setTransitionName("carrier" + order.getIndex());
carrierTextView.setText(order.getCarrier());
numberTextView.setTransitionName("number" + order.getIndex());
numberTextView.setText(String.valueOf(order.getNumber()));
pickerTextView.setTransitionName("picker" + order.getIndex());
pickerTextView.setText(order.getPicker());
locationTextView.setTransitionName("location" + order.getIndex());
locationTextView.setText(order.getPosition());
carrierTextView.setText("Lorem Ipsum");
numberTextView.setText("Dolor sit amet");
pickerTextView.setText("consectetur adipiscing elit");
locationTextView.setText("Mauris semper");
}
}
orderCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getParentFragmentManager().popBackStack();
}
});
Transition transition = TransitionInflater.from(getContext()).inflateTransition(R.transition.card_transition);
setSharedElementEnterTransition(transition);
setSharedElementReturnTransition(transition);
return root;
}
xml that goes with fragment above
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context=".ui.orders.OrdersFragment">
<TextView
android:transitionName="bonnen_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="#string/orders"
android:textColor="#color/secondary"
android:textSize="40sp"
android:textStyle="bold"
android:typeface="normal" />
<androidx.cardview.widget.CardView
android:id="#+id/order_card"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardBackgroundColor="#color/primaryLight"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:layout_margin="25dp">
<LinearLayout
android:transitionName="order_card_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="10dp">
<TextView
android:id="#+id/carrier_text_view"
android:transitionName="carrier_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/secondary"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/id_text_view"
android:transitionName="id_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/secondary" />
<TextView
android:id="#+id/picker_text_view"
android:transitionName="picker_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/secondary" />
<TextView
android:id="#+id/location_text_view"
android:transitionName="location_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/secondary" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
This is what it looks like with setReorderingAllowed(true);
This is what it looks like without setReorderingAllowed(true);
EDIT
After applying the answer given by ianhanniballake I got it working.
Here is what I did for future reference.
The only changes I made is in the OrdersFragment class.
I removed the override of the onCreate() method.
I removed the startPostponedEnterTransition(); from my fetchOrders() method and I added
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
postponeEnterTransition();
final ViewGroup parentView = (ViewGroup) view.getParent();
parentView.getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
parentView.getViewTreeObserver().removeOnPreDrawListener(this);
startPostponedEnterTransition();
return true;
}
});
super.onViewCreated(view, savedInstanceState);
}
That's it
As per the Use shared element transitions with a RecyclerView guide, you're calling startPostponedEnterTransition() too early - after setting your data (and calling notifyDataSetChanged() to inform the adapter), you need to wait until the RecyclerView is actually measured and laid out. This requires that you add an OnPreDrawListener and only call startPostponedEnterTransition() once that fires.
In Kotlin you need to start the transition in doOnPreDraw callback of the recyclerView like below:
recyclerView.doOnPreDraw {
startPostponedEnterTransition()
}

Master/Detail layout not rendering

I'm trying to make an app that fetches a book list from an API and displays it on the master list and, upon clicking, it displays the details. It works fine with mobiles, but I can't get it to work with tablets and since there's no error I can't find out where I went wrong.
On tablets it renders as if on a phone instead of rendering the two pane view.
I'm using a single activity with fragments.
"Main" activity:
public class ItemListActivity extends AppCompatActivity {
public static FragmentManager fragmentManager;
private boolean isTwoPane = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
determinePaneLayout();
fragmentManager = getSupportFragmentManager();
if(isTwoPane){
//fragmentManager.beginTransaction().add(R.id.master_dual, new ItemsListFragment()).commit();
fragmentManager.beginTransaction().add(R.id.flDetailContainer, new ItemDetailFragment()).commit();
fragmentManager.beginTransaction().add(R.id.fragmentContainer, new ItemsListFragment()).commit();
} else {
fragmentManager.beginTransaction().add(R.id.fragmentContainer, new ItemsListFragment()).commit();
}
}
private void determinePaneLayout() {
FrameLayout fragmentItemDetail = (FrameLayout) findViewById(R.id.flDetailContainer);
// If there is a second pane for details
if (fragmentItemDetail != null) {
isTwoPane = true;
}
}
Item List Fragment:
public class ItemsListFragment extends Fragment {
private ArrayList<Book> bookList;
private ArrayList<String> bookNames;
private ArrayAdapter<Book> bookArrayAdapter;
private ArrayAdapter<String> bookNamesAdapter;
private ApiInterface apiInterface;
private ListView lvItems;
private static final String bookKey = "newBook";
private static Book nBook;
public ItemsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_items_list,
container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lvItems = view.findViewById(R.id.lvItems);
bookNames = new ArrayList<>();
//bookNames.add(0, "Gabriel");
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<ArrayList<Book>> call = apiInterface.getBooks();
call.enqueue(new Callback<ArrayList<Book>>() {
#Override
public void onResponse(Call<ArrayList<Book>> call, Response<ArrayList<Book>> response) {
bookList = new ArrayList<>();
bookList = response.body();
bookArrayAdapter = new ArrayAdapter<>(getContext(),
android.R.layout.simple_list_item_activated_1, bookList);
lvItems.setAdapter(bookArrayAdapter);
}
#Override
public void onFailure(Call<ArrayList<Book>> call, Throwable t) {
}
});
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nBook = bookList.get(i);
if(view.findViewById(R.id.flDetailContainer) != null){
ItemListActivity.fragmentManager.beginTransaction().replace(R.id.flDetailContainer, ItemDetailFragment.newInstance(nBook)).addToBackStack(null).commit();
} else {
ItemListActivity.fragmentManager.beginTransaction().replace(R.id.fragmentContainer, ItemDetailFragment.newInstance(nBook)).addToBackStack(null).commit();
}
}
});
}`
Item Detail Fragment:
public class ItemDetailFragment extends Fragment {
private static final String bookKey = "newBook";
private static Book nBook;
private TextView title;
private TextView isbn;
private TextView currency;
private TextView price;
private TextView author;
public static ItemDetailFragment newInstance(Book book) {
ItemDetailFragment fragment = new ItemDetailFragment();
Bundle args = new Bundle();
args.putSerializable(bookKey, book);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
nBook = (Book)getArguments().getSerializable(bookKey);
Log.v("BundleOK", "BundleOK");
} else {
Log.v("Bundle Nulo", "Bundle nulo");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate view
View view = inflater.inflate(R.layout.fragment_item_detail,
container, false);
// Return view
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
title = view.findViewById(R.id.tvTitle);
isbn = view.findViewById(R.id.tvIsbn);
currency = view.findViewById(R.id.tvCurrency);
price = view.findViewById(R.id.tvPrice);
author = view.findViewById(R.id.tvAuthor);
title.setText(nBook.getTitle());
isbn.setText("ISBN: " + nBook.getIsbn());
currency.setText("Currency: "+ nBook.getCurrency());
price.setText("Price: "+ String.valueOf((long)nBook.getPrice()/100));
author.setText("Autor: "+nBook.getAuthor());
}
XML for dual pane:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:showDividers="middle"
android:baselineAligned="false"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/fragmentItemsList"
android:name="gabrielgomes.studio.com.itemretrieve.ItemsListFragment"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
tools:layout="#layout/fragment_items_list" />
<View android:background="#000000"
android:layout_width="1dp"
android:layout_height="wrap_content"
/>
<FrameLayout
android:id="#+id/flDetailContainer"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
XML for the Main Activity (Item List Activity)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
XML for the Item Detail Fragment:
<?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" >
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="110dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:fontFamily="#font/baskervillebt"
android:gravity="center"
android:text="Item Title"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvIsbn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvTitle"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:fontFamily="#font/baskervilleitalicbt"
android:text="Item Body"
android:textSize="16sp" />
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvIsbn"
android:layout_centerHorizontal="true"
android:layout_marginTop="47dp"
android:fontFamily="#font/baskervilleitalicbt"
android:text="Price"
android:textSize="16sp" />
<TextView
android:id="#+id/tvCurrency"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvPrice"
android:layout_centerHorizontal="true"
android:fontFamily="#font/baskervilleitalicbt"
android:layout_marginTop="44dp"
android:text="Currency"
android:textSize="16sp" />
<TextView
android:id="#+id/tvAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvCurrency"
android:fontFamily="#font/baskervilleitalicbt"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="Author"
android:textSize="16sp" />
</RelativeLayout>
I've been cracking my head for 5 days now, so any help is really appreciated! I tried a number of tutorials and searched SO thoroughly but no go!
Cheers!
I believe you have two copies activity_item_list.xml layout file and one is res/layout/ folder and another one is in res/layout-sw600dp/ folder.
sw600dp --> Screen width above 600dp use this layout else if less than 600dp use default layout file.
And also you make sure keep same attribute ids same in both the layout files.

Accessing UI elements from fragment class

i have a class which extends fragment class as below:
public class FragmentCreateGroup extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ImageView group=(ImageView)findViewById(R.id.group_image);//shows error here
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment_creategroup, container,false);
}
}
which is associated to the following xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/cr_group_grpname_desc"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/group_image"
android:layout_width="139dp"
android:layout_height="144dp"
android:src="#drawable/background" />
<EditText
android:id="#+id/cr_group_grpname_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="37dp"
android:contentDescription="#string/cr_group_grpname_desc"
android:ems="10"
android:hint="#string/cr_group_grpname_hint"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/cr_group_creategrp_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="42dp"
android:background="#drawable/greenbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/cr_group_creategrp_btn_label" />
</LinearLayout>
I tried to access the ImageView in the fragment layout using findViewById(). Since I didn't extend Activity class I was unable to perform this action. Is there any way to access the UI Elements from a non activity class? if any how to perform?
You need to get the view after you inflate it in onCreateView
public class FragmentCreateGroup extends Fragment {
private ImageView group;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_creategroup, container, false);
group = (ImageView) v.findViewById(R.id.group_image);
group.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
group.setImageDrawable(); // set image here
}
});
return v;
}
}

Radio group not show when fragment change

I want to change fragment(#+id/content_frame) using fragment
manager on Radiobutton (used as a tab ) but ononCheckedChanged when fragment load
my radio button gone it's not shown .
here is my main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioGroup
android:id="#+id/buttongroup1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<at.bookworm.widget.TabControlButton
android:id="#+id/opt_ct"
style="#style/Widget.Holo.SegmentedControl"
android:checked="true"
android:text="City Taxi"
android:textColor="#color/black"
android:textStyle="normal" />
<at.bookworm.widget.TabControlButton
android:id="#+id/opt_os"
style="#style/Widget.Holo.SegmentedControl"
android:text="Outstation"
android:textColor="#color/black"
android:textStyle="normal" />
<at.bookworm.widget.TabControlButton
android:id="#+id/opt_lo"
style="#style/Widget.Holo.SegmentedControl"
android:text="Local"
android:textColor="#color/black"
android:textStyle="normal" />
</RadioGroup>
<FrameLayout android:id="#+id/content_frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
<ListView
android:id="#+id/left_drawer"
style="?android:attr/dividerHorizontal"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/silver_two"
android:choiceMode="singleChoice" >
<!--
<LinearLayout
android:id="#+id/left_drawer"
android:orientation="vertical"
android:layout_width="240dp"
android:layout_height="match_parent">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/my_account"/>
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="Test"/>
</LinearLayout>
-->
</ListView>
</android.support.v4.widget.DrawerLayout>
i replacing using fragment using fragment manager in my MainActivity
here is the code
public class MainActivity extends Activity{
Fragment mainFragment = new MainFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radioGroup = (RadioGroup) findViewById(R.id.buttongroup1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.content_frame, mainFragment).commit();
}
});
}
after radio group chacked it goes on
public class MainFragment extends Fragment{
static View rootView;
------
----
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.route_fragment, container, false);
} catch (InflateException e) {
}
return rootView;
}
Please check that you are doing something like this in your fragment :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
rather than setContentView
This is a good resource:
http://developer.android.com/training/basics/fragments/creating.html

Android: how to get the views of a Fragment

In a class i am adding a Fragment programatically.
This Fragment contains a Button, which i want to have an onClick implementation.
Here is the class i have:
public class ShareProduct extends SherlockFragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.share_product);
FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
ProductFragment1 fragment = new ProductFragment1();
fragmentTransaction.add(R.id.share_product_parent, fragment);
fragmentTransaction.commit();
Button done_button = (Button) fragment.getView().findViewById(
R.id.done_product_1);
done_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ProductFragment2 fragment = new ProductFragment2();
fragmentTransaction
.replace(R.id.share_product_parent, fragment);
fragmentTransaction.commit();
}
});
}
}
and my ProductFragment1 class is:
public class ProductFragment1 extends SherlockFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.share_product_1, container, false);
return view;
}
}
and the layout my main class uses is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/share_product_parent"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="right|center_vertical"
android:orientation="horizontal" >
</RelativeLayout>
and the layout my ProductFragment1 uses is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dp" />
<EditText
android:id="#+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tv1"
android:textSize="25dp" />
<Button
android:id="#+id/done_product_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/et1"
android:text="Done" />
</RelativeLayout>
The problem is:
I am getting a NullPointerException at this line in my main class:
Button done_button = (Button) fragment.getView().findViewById(R.id.done_product_1);
done_button.setOnClickListener ....
when i searched for what getView() on a fragment returns. I found out that it returns the view from onCreateView();
I checked it doesn't return null.
Thank You
You are on the wrong track here. You get the NPE because the Fragments views is not created yet. Fragments also have a lifecycle just like Activities.
What you should be doing is assigning the OnClickListener inside your Fragments onViewCreated() method. And from there... you should create a callback and notify your hosting Activity of the event.

Categories

Resources