Hi guys i started learning android development about 2 days ago.. So was trying out with a basic application to increment and decrement.
Everything is okay but when i'm testing the application even on the emulator, i get a message "Unfortunately, application "
I tried debugging the code and found that Even after declaring a statement findViewById(), my variables are pointing to null. And i think that's the reason for this error.. heres my code, in MainActivity.java. Please help me out!
public class MainActivity extends ActionBarActivity {
/* Your original code */
/*
TextView sum;
Button increment;
Button decrement;
*/
int total;
/* My interpretation */
protected static TextView sum;
protected static Button increment;
protected static Button decrement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.findViewById();
total = 0;
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
total++;
sum.setText("Sum is "+total);
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
total--;
sum.setText("Sum is "+total);
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
/* Your original code (moved to fragment) */
/*
private void findViewById() {
sum = (TextView) findViewById(R.id.tv); // sum points to null
increment = (Button) findViewById(R.id.inc); //increment points to null
decrement = (Button) findViewById(R.id.dec); // decrement points to null
}
*/
EDIT ::
placeholder fragment ::
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
/* added */
Context ctx = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
/* added */
init();
}
/* added */
private void init()
{
final View v = getView();
ctx = getActivity().getApplicationContext();
MainActivity.sum = (TextView) v.findViewById(R.id.tv); // sum points to null
MainActivity.increment = (Button) v.findViewById(R.id.inc); //increment points to null
MainActivity.decrement = (Button) v.findViewById(R.id.dec); // decrement points to null
}
}
here is the layout ::
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.vishal.Simplecalc.MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/tv"
android:text="#string/sumView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_gravity="center"
tools:context=".MainActivity"
/>
<Button
android:id="#+id/inc"
android:text="#string/inc"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_gravity="center"
android:textStyle="bold"
tools:context=".MainActivity"
/>
<Button
android:id="#+id/dec"
android:text="#string/dec"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_gravity="center"
android:textStyle="bold"
tools:context=".MainActivity"
/>
</LinearLayout>
Just guessing here (you haven't added the name for your xml layout).
I'm guessing you're probably confusing your layouts and just posted fragment_main.xml which actually has the content your code is believing to be held in activity_main, which causes your code to return nulls when you're assigning the findViewById()
I think the problem is that PlaceholderFragment is setting a new layout, and that doesn't allow the text to be changed.
Sometimes it can be because of emulators, create new emulator or try it with your real device .
Related
I'm trying to change TextView in my fragment layout, however I'm getting null value when calling findViewById no matter what.
Here's my fragment layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.kubacm.myweather.ShowMeWeather">
<TextView
android:id="#+id/city_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#android:color/white" />
</RelativeLayout>
Calling fragment from main activity:
#Override public void showWeather(JSONObject data){
Bundle bundle = new Bundle();
bundle.putString("data",data.toString());
ShowMeWeather wf = new ShowMeWeather();
wf.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.activity_main,wf).addToBackStack(null).commit();
}
and in fragment:
public class ShowMeWeather extends Fragment {
Typeface weatherFont;
TextView cityField;
public ShowMeWeather() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_show_me_weather, container, false);
cityField = (TextView)rootView.findViewById(R.id.city_field);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
weatherFont = Typeface.createFromAsset(getActivity().getAssets(),"fonts/weather.ttf");
renderWeather();
}
public void renderWeather(){
try{
cityField.setText("Here should go my text");
}catch (Exception e){
Log.e("Simple Weather","there was an errror");
}
}
}
I have tried cleaning and rebuilding my project in Android Studio and still keep getting NullPointerException when I try cityField.SetText
onCreateView method is called after onCreate method, so cityField is not yet initialized
Check fragment lifecycle here here
Call your renderWeather method after onCreateView is completed
So I've searched for hours trying to find an answer to this specific problem I'm having with no luck. Would be great if someone can help me out.
So essentially I have a MainActivity.java, FragmentA.java, activity_main.xml, and fragment.xml. So what fragment.xml has is just a container that have 3 buttons in a box that when pressed Start showing a number starting from 3 as the buttons text. So when you click the button again, it changes the button text to 2 and then 1 and then 0 and then back to 3. All the logic that decrements the numbers and changes the button text to that number is in the FragmentA.java class. All that's logic is working, I've tested it. Finally I create and add FragmentA dynamically to MainActivity's activity_main.xml LinearLayout when an add button in actionbar is clicked.
So now when you press the add button in the actionbar in MainActivity, the fragment.xml view is correctly appended to activity_main.xml's LinearLayout. The problem is, only the first fragment that's appended in the LinearLayout is working (numbers decrement) when button is clicked. The other fragment copies are not working or doing anything, but just showing. So the buttons decrement logic is only working for the first added view. Why is that? I thought the point of fragments was to elimanate duplication. I'm guessing this is some ID issue with the same fragment being created multiple times? Any idea on how to fix this?
FragmentA.java
Button b1, b2, b3;
int[] mCounter = {3, 3, 3};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, null);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getActivity().findViewById(R.id.button);
b1.setOnClickListener(this);
b2 = (Button) getActivity().findViewById(R.id.button2);
b2.setOnClickListener(this);
b3 = (Button) getActivity().findViewById(R.id.button3);
b3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button:
b1.setText(Integer.toString(mCounter[0]));
decrementCounterByButtonPosition(0);
break;
case R.id.button2:
b2.setText(Integer.toString(mCounter[1]));
decrementCounterByButtonPosition(1);
break;
case R.id.button3:
b3.setText(Integer.toString(mCounter[2]));
decrementCounterByButtonPosition(2);
break;
}
}
public void decrementCounterByButtonPosition(int counterId) {
if (mCounter[counterId] != 0) {
mCounter[counterId]--;
} else {
mCounter[counterId] = 3;
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add_exercise) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentA ContainerFragment = new FragmentA();
fragmentTransaction.add(R.id.container, ContainerFragment, "HELLO");
fragmentTransaction.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
activity_main.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"
android:background="#1FDA9A">
<LinearLayout
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"
android:orientation="vertical"
android:id="#+id/container">
</LinearLayout>
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="wrap_content"
android:paddingTop="0dp"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/globalContainer"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#fff"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:backgroundTint="#333"
android:gravity="center_vertical|center_horizontal">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:maxWidth="10dp"
android:maxHeight="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:maxWidth="10dp"
android:maxHeight="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button3"
android:maxWidth="10dp"
android:maxHeight="10dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
</LinearLayout>
</LinearLayout>
Any help appreciated. Thanks :D
In addition to Abdullah Asendar's answer, you have another thing to fix.
The problem is with the way you are getting your views.
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
b1 = (Button) getActivity().findViewById(R.id.button);
b1.setOnClickListener(this);
b2 = (Button) getActivity().findViewById(R.id.button2);
b2.setOnClickListener(this);
b3 = (Button) getActivity().findViewById(R.id.button3);
b3.setOnClickListener(this);
}
This finds views from the Activity, not from your fragment.
The correct way to do this is:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment, container, false);
b1 = (Button) v.findViewById(R.id.button);
b1.setOnClickListener(this);
b2 = (Button) v.findViewById(R.id.button2);
b2.setOnClickListener(this);
b3 = (Button) v.findViewById(R.id.button3);
b3.setOnClickListener(this);
return v;
}
and get rid of your onActivityCreated override because it no longer does anything special.
notice the subtle change View v = inflater.inflate(R.layout.fragment, container, false);
I am not quite sure but I think the problem is in the ContainerFragment Object
FragmentA ContainerFragment = new Fragment();
try to change it to :
FragmentA ContainerFragment = new FragmentA();
if you can't pass the object fragmentTransaction.add
do this:
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
I hope this helps.
I have implemented a ViewPager which connects multiple Fragments together to give off that 'scrolling view' experience as you might already know. Anyhow I have a button on my first fragment that needs to scroll the user to the second fragment. How do I get this done folks? Here's my code:
ViewPager XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
Fragment 1:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="left"
android:layout_marginLeft="15dp"
android:layout_marginTop="25dp"
android:text="Step 1"
android:textColor="#ffffff"
android:textSize="50dp" />
<Button
android:id="#+id/step1Btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="5sp"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:text="Next Step"
android:textColor="#FFFFFF"
android:textSize="30sp" />
</LinearLayout>
</RelativeLayout>
In order to make this post short, let's say the second fragment has the same XML.
So we have TWO fragments. Here's the fragment java class:
public class RegisterPageOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.registration_page1, container, false);
Button nextStep = (Button) v.findViewById(R.id.step1Btn);
nextStep.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Where I want to call the SECOND FRAG
}
});
return v;
}
public static RegisterPageOne newInstance(String text) {
RegisterPageOne f = new RegisterPageOne();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
help me out please :)
You can use the setCurrentItem(int item,boolean smoothScroll) method of your viewPager object to achieve this. Here is the documentation.
Saw your followup question about how to refer to the ViewPager, from your Fragment. It's pretty convoluted, for a relative newbie like me, but, I think I can get all of it... I'll give you what I did in my code. Set up a listener in the ViewPager:
public class PageViewActivity extends FragmentActivity
implements PageDisplayPortFrag.OnLinkExpectedListener {
...
}
This gets referenced in your Fragment:
private OnLinkExpectedListener mListenerLink;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListenerLink = (OnLinkExpectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnLinkExpectedListener");
}
}
#Override
public void onDetach() {
mListenerLink = null;
super.onDetach();
}
// THIS IS THE METHOD CALLED BY THE BUTTON CLICK !!!
public void linkExpected(String ticker) {
if (mListenerLink != null) {
mListenerLink.onLinkActivity(ticker);
}
}
public interface OnLinkExpectedListener {
public void onLinkActivity(String ticker);
}
And, then, a method gets called in the ViewPager:
#Override
public void onLinkActivity(String ticker) {
// receive ticker from port click; user wants to view page in webview, for this security
//Toast.makeText(this, "Ticker item clicked: " + ticker, Toast.LENGTH_SHORT).show();
// NEHARA, YOU MAY OR MAY NOT NEED TO DO STUFF HERE
// THIS IS WHAT I NEEDED TO DO; LEAVING IT FOR THE
// getFragmentTag() EXAMPLE -- WHICH CAME FROM Stack Overflow POSTERS
// get all-important fragment tag
String frag_Tag = getFragmentTag(pager.getId(),1);
// use tag to get the webview fragment
PageXYZWebviewFrag xyzWeb = (PageXYZWebviewFrag)
getSupportFragmentManager().findFragmentByTag(frag_Tag);
// send request to the webview fragment
xyzWeb.loadPageForSelectedSecurity(ticker);
// SET THE DESIRED FRAGMENT, assumes I know the fragment number
// from when I set up the ViewPager
// switch to the webview fragment
pager.setCurrentItem(1);
}
// fragment tag getter -- very important, yet has been elusive
private String getFragmentTag(int viewPagerId, int fragmentPosition) {
return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
}
I have a fragment with an XML layout file. in it I have an 2 clickable ImageViews.
for each ImageView I set an onClick method for example: android:onClick="commentFragmentRemoveOnClick".
In the FragmentActivity (The Activity no the Fragment) I defined it this way:
public void commentFragmentRemoveOnClick(View v)
{
}
No this Fragment is of type CommentFragment and it has a public void getFragmentTag()method
to get it's tag that I save in earlier time. I need to get an instance of the fragment in which the image was clicked to get it's tag.
I tried:
((CommentFragment)v).getParentFragment().getFragmentTag();
and:
((CommentFragment)v).getParent().getFragmentTag();
but eclipse gives me error on both of them, how is this done properly?
To make it more clear this is my CommentFragment:
public class CommentFragment extends Fragment {
private final static String TAG = CommentFragment.class.getSimpleName();
private String fragmentTag;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.comment_fragment_layout,
container, false);
Bundle bundle = getArguments();
String text = bundle.getString("comment");
String fullUser = bundle.getString("user");
String user = fullUser.substring(0, fullUser.indexOf("#"));
String at = bundle.getString("at");
TextView tvCmment = (TextView) rootView.findViewById(R.id.tvComment);
TextView tvUser = (TextView) rootView.findViewById(R.id.tvUser);
TextView tvAt = (TextView) rootView.findViewById(R.id.tvDate);
tvCmment.setText(text);
tvUser.setText(user);
tvAt.setText(at);
return rootView;
}
public void setText(String item)
{
TextView view = (TextView) getView().findViewById(R.id.tvComment);
view.setText(item);
}
public void setFragmentTag(String tag)
{
this.fragmentTag = tag;
}
public String getFragmentTag()
{
return this.fragmentTag;
}
}
and the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llCommentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/try2">
<TextView
android:id="#+id/tvUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvComment"
android:layout_alignParentTop="true"
android:background="#color/my_gray"
android:text="demo"
android:textStyle="bold"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvComment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvDate"
android:padding="5dp"
android:text="This task is described in more details if you click on it."
android:textColor="#color/my_even_darker_gray" />
<TextView
android:id="#+id/tvAt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingRight="5dp"
android:textColor="#color/my_even_darker_gray"
android:layout_toRightOf="#+id/tvUser"
android:background="#color/my_gray"
android:text="at" />
<TextView
android:id="#+id/tvDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvAt"
android:layout_alignBottom="#+id/tvAt"
android:layout_toRightOf="#+id/tvAt"
android:background="#color/my_gray"
android:text="12/02"
android:textColor="#color/my_even_darker_gray" />
<ImageView
android:id="#+id/iEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvComment"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentEditOnClick"
android:src="#drawable/add_comment_button" />
<ImageView
android:id="#+id/iRemove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/iEdit"
android:layout_toRightOf="#+id/iEdit"
android:layout_marginRight="4dp"
android:clickable="true"
android:contentDescription="#drawable/add_comment_button"
android:onClick="commentFragmentRemoveOnClick"
android:src="#drawable/add_comment_button" />
</RelativeLayout>
I would love for a little assistance.
Thanks.
I have a general advice for you that would solve your problem and help you in the future -
don't use android:onClick in the xml file, use setOnClickListener in the code itself - need to avoid mixing your views with other parts of the app as much as possible.
Try to keep the Fragment independent of its activity.
If the image is part of the fragment, why does the listener is part of the FragmentActivity?
Use setOnClickListener in the fragment itself, and you might be able to use this Framgent in other pats of the app without being depended on the Activity.
It would also solve your problem of identifying the fragment in which the image was clicked.
v is not an instance of Fragment, that's why Eclipse does not like your code. If you want the instance of a fragment you have to use the FragmentManager and one of its findFragmentByXXX methods.
To get the instance of the fragment that the ImageView was clicked in I did the following:
in the Fragment I set two onClickListeners for both of the images like this:
iEdit = (ImageView)rootView.findViewById(R.id.iEdit);
iEdit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed edit button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentEditOnClick(fragmentTag);
}
});
iRemove = (ImageView)rootView.findViewById(R.id.iRemove);
iRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d(TAG, "pressed remove button");
((PicturesAndCommentsActivity) getActivity()).commentFragmentRemoveOnClick(fragmentTag);
}
});
and in the fragment activity I defined those two methods like this:
public void commentFragmentRemoveOnClick (String tag)
{
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.remove(fragmentManager.findFragmentByTag(tag)).commit();
}
for removing the fragment, and Now I'm working on editing the fragment.
I have created a compound control with the following:
Java
public class QuantityBox extends LinearLayout
{
private TextView partNmbr;
private Button decrease;
private Button increase;
private EditText quantity;
private int qty;
public QuantityBox(Context context)
{
super(context);
// load views
loadViews();
}
/**
* This constructor is necessary in order to use this compound
* control in an XML layout.
* #param context Application context
* #param attrs
*/
public QuantityBox(Context context, AttributeSet attrs)
{
super(context, attrs);
// inflate the view we created
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.quantity_box, this);
// load views
loadViews();
}
/**
* Load the views created from the constructor
*/
private void loadViews()
{
this.qty = 1;
partNmbr = (TextView) findViewById(R.id.tvPartNmbr);
decrease = (Button) findViewById(R.id.btnDecrease);
increase = (Button) findViewById(R.id.btnIncrease);
quantity = (EditText) findViewById(R.id.etQty);
// set initial text
quantity.setText(this.qty);
decrease.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// decrease quantity
qty--;
// update view
quantity.setText(qty);
}
});
increase.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// increase quantity
qty++;
// update view
quantity.setText(qty);
}
});
}
}
XML
<?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" >
<TextView
android:id="#+id/tvPartNmbr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
/>
<Button
android:id="#+id/btnDecrease"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="-"
/>
<EditText
android:id="#+id/etQty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
/>
<Button
android:id="#+id/btnIncrease"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="+"
/>
</LinearLayout>
And I trying to create it here, programmatic-ally:
public class CustomHeaderActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_title_bar);
QuantityBox qb = new QuantityBox(this);
}
}
Why isn't this working? Am I missing a step? (NullPointerException is thrown.)
The widgets will not be there by the time you call loadViews(). Wait for that until onFinishInflate().
You never inflate your view in the constructor that only takes the Context argument, meaning quantity.setText(...); will throw a NPE because quantity wasn't found in findViewById(...);