My application (min level 13) is an Activity that uses tabs in the action bar to manage a couple fragments, very similar to this.
Now, the activity starts a service which does continuous computation and returns values which I would like to display in the Fragments. The Activity - Service communication is implemented through broadcast receivers and the Activity shuffles the data off to the appropriate Fragment.
Everything seems setup correctly and the data makes it to the Fragment update method but when I try to display the new values in textviews, the new values are never displayed.
The code to change the textviews:
TextView tv = (TextView) getView().findViewById(R.id.fieldNavGpsTime);
Double doub = input.getDoubleExtra("com.some.thing.GPS_TIME", -1.0);
tv.setText(doub.toString());
The code to call the Fragments update methods from the broadcast receiver in the Activity:
NavigationGuiFragment navfrag = (NavigationGuiFragment) getFragmentManager().findFragmentByTag("navigation");
if (navfrag != null && navfrag.isResumed())
navfrag.UpdateNavUI(intent);
I've noticed that isVisible() doesn't seem to ever return true, but I'm not sure what it means or how to change it.
Additionally, I can't seem to add an imageview to a Fragment programmatically. Here's the code (which resides in onActivityCreated()):
this.compass = new BasicCompass(getActivity());
LinearLayout ll = (LinearLayout) getView().findViewById(R.id.nav_hrztl_lnly);
ll.addView(this.compass);
The BasicCompass constructor takes a Context, admittedly I'm not completely sure what I'm passing in is correct.
The code for this was more or less taken from a working Activity and dropped into a Fragment to allow for tabs. I'm open to suggestion in regards to changing the structure of the code.
Thanks for any help.
EDIT
The xml layout of the Fragment:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/nav_hrztl_lnly"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:focusable="true"
android:focusableInTouchMode="true"
android:baselineAligned="false" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="600dp"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true" >
<EditText
android:id="#+id/labelNavGpsTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/gps_time" />
<EditText
android:id="#+id/fieldNavGpsTime"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_3_digits"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/labelNavLatitude"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/latitude" />
<EditText
android:id="#+id/fieldNavLatitude"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_6_digits"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/labelNavLongitude"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/longitude" />
<EditText
android:id="#+id/fieldNavLongitude"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_6_digits"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/labelNavAltitude"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/altitude" />
<EditText
android:id="#+id/fieldNavAltitude"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_3_digits"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/labelNavRoll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/roll" />
<EditText
android:id="#+id/fieldNavRoll"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_6_digits"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/labelNavPitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/pitch" />
<EditText
android:id="#+id/fieldNavPitch"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_6_digits"
android:inputType="numberDecimal" />
<EditText
android:id="#+id/labelNavAzimuth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/azimuth_heading" />
<EditText
android:id="#+id/fieldNavAzimuth"
style="#style/field_padding"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/zero_6_digits"
android:inputType="numberDecimal" />
<LinearLayout
android:id="#+id/nav_rdbtn_lnly"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rdbtnNavGpsAvailability"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/gps_avail" />
<RadioButton
android:id="#+id/rdbtnNavZuptStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/zupt_stat" />
</LinearLayout>
</LinearLayout>
And the Fragment that uses it:
public class NavigationGuiFragment extends Fragment
{
private RadioButton gpsRdBtn;
private RadioButton zuptRdBtn;
private BasicCompass compass;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View fragview = inflater.inflate(R.layout.navigation_fragment, container, false);
// sets up the rose image that serves as a compass in the GUI
this.compass = new BasicCompass(getActivity());
LinearLayout ll = (LinearLayout) fragview.findViewById(R.id.nav_hrztl_lnly);
ll.addView(this.compass);
return fragview;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
getActivity().setContentView(R.layout.navigation_fragment);
//Initialize the radio buttons
gpsRdBtn = (RadioButton) getView().findViewById(R.id.rdbtnNavGpsAvailability);
gpsRdBtn.setChecked(false);
zuptRdBtn = (RadioButton) getView().findViewById(R.id.rdbtnNavZuptStatus);
zuptRdBtn.setChecked(false);
}
#Override
public void onResume()
{
super.onResume();
if (!IsMyServiceRunning())
{
gpsRdBtn.setChecked(false);
zuptRdBtn.setChecked(false);
}
}
public void UpdateNavUI(Intent input)
{
TextView tv = (TextView) getView().findViewById(R.id.fieldNavGpsTime);
Double doub = input.getDoubleExtra("com.some.thing.GPS_TIME", -1.0);
tv.setText(doub.toString());
tv = (TextView) getView().findViewById(R.id.fieldNavLatitude);
doub = input.getDoubleExtra("com.some.thing.LATITUDE", 100000.0);
tv.setText(doub.toString());
tv = (TextView) getView().findViewById(R.id.fieldNavLongitude);
doub = input.getDoubleExtra("com.some.thing.LONGITUDE", 100000.0);
tv.setText(doub.toString());
tv = (TextView) getView().findViewById(R.id.fieldNavAltitude);
doub = input.getDoubleExtra("com.some.thing.ALTITUDE", -1.0);
tv.setText(doub.toString());
tv = (TextView) getView().findViewById(R.id.fieldNavRoll);
doub = input.getDoubleExtra("com.some.androidndk.ROLL", 361.0);
tv.setText(doub.toString());
tv = (TextView) getView().findViewById(R.id.fieldNavPitch);
doub = input.getDoubleExtra("com.some.thing.PITCH", 361.0);
tv.setText(doub.toString());
tv = (TextView) getView().findViewById(R.id.fieldNavAzimuth);
doub = input.getDoubleExtra("com.some.thing.AZIMUTH", 361.0);
tv.setText(doub.toString());
this.compass.SetDirection(doub.floatValue());
boolean bool = input.getBooleanExtra("com.some.thing.ZUPT_STATUS", false);
zuptRdBtn.setChecked(bool);
UpdateGpsIndicator(input);
}
public void UpdateGpsIndicator(Intent input)
{
boolean bool = input.getBooleanExtra("com.some.thing.GPS_ON", false);
gpsRdBtn.setChecked(bool);
}
private boolean IsMyServiceRunning()
{
ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if ("com.some.thing.Service".equals(service.service.getClassName()))
return true;
}
return false;
}
}
this line:
getActivity().setContentView(R.layout.navigation_fragment);
should be called in Activity.onCreate() and make sure it is just called once. In your code it will be called every time Fragment moves to active state. And the TextView and RaidoButton stuff will be reset to state define in the layout xml.
Checkout Fragment lifecycle here.
UPDATE:
Some view widget's state will be kept by Activity, e.g TextView. Try move your setXXX() method to onResume(). I have experience that setXXX() is not working in onActivityCreated() but works well in onResume().
Related
I already read tun of code here or anywhere else. And i am realy confused. I found on web simple prog on add and remove edittext with remove button. But when i add text view more then ones, it has same id, but i need that text what is wrote inside. And if was possible i need next id with letters, not in number.
here is my code:
public class MainActivity extends AppCompatActivity {
private LinearLayout parentLinearLayout1;
private LinearLayout parentLinearLayout2;
TextView a1;
TextView txt;
#Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
parentLinearLayout1 = (LinearLayout) findViewById (R.id.parent_linear_layout1);
parentLinearLayout2 = (LinearLayout) findViewById (R.id.parent_linear_layout2);
a1 = (TextView) findViewById (R.id.textView5);
txt = (EditText) findViewById (R.id.txt);
}
public void onAddField( View v ) {
LayoutInflater inflater = (LayoutInflater) getSystemService (Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate (R.layout.field, null);
parentLinearLayout1.addView (rowView, parentLinearLayout1.getChildCount () );
Button addbtn = (Button) findViewById (R.id.add_field_button);
int id = addbtn.getId ();
a1 = (TextView) findViewById (R.id.textView5);
a1.setText (id + "");
}
public void onDelete( View v ) {
parentLinearLayout1.removeView ((View) v.getParent ());
Button del = (Button) findViewById (R.id.deletebuton1);
// c=(EditText)findViewById (R.id.number_edit_text);
int id = del.getId ();
a1 = (TextView) findViewById (R.id.textView5);
a1.setText (id + "");
}
}
activity_main xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Město" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent_linear_layout1"
android:layout_width="374dp"
android:layout_height="120dp"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<EditText
android:id="#+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="text" />
<Button
android:id="#+id/add_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="#555"
android:onClick="onAddField"
android:paddingLeft="5dp"
android:text="Add Field"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
and field xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:inputType="text" />
<Button
android:id="#+id/deletebuton1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete">
</LinearLayout>
Its even possible or this code is unseless and i must start again?
Thanks for answer.
I have an OnClickListener that listens to Button A clicks. I also have 2 TextViews below the Button.
I want that on every click on Button A, the 2 TextViews will switch their places between them, like this:
Before clicking:
TextView A
TextView B
After clicking:
TextView B
TextView A
How can I do it? Is there a special function that meant to do that? or some kind of a trick? Thanks!
actvity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="start"
tools:context="com.intap.tof.MainActivity">
<TextView
android:id="#+id/txtA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp"
android:visibility="visible"/>
<TextView
android:id="#+id/txtB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtA
android:layout_marginTop="83dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="visible"
android:textSize="20dp" />
</RelativeLayout>
MainActivity.java:
txtA = (TextView) findViewById(R.id.txtA);
txtB = (TextView) findViewById(R.id.txtB);
float mAX = txtA.getX();
float mAY = txtA.getY();
float mBX = txtB.getX();
float mBY= txtB.getY();
txtA.setX(mBX);
txtA.setY(mBY);
txtB.setX(mAX);
txtB.setY(mAY);
Trick is changing the x and y axis of both views :
Your xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="start"
tools:context="com.intap.tof.MainActivity">
<TextView
android:id="#+id/txtA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp"
android:text="A"
android:tag="A"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/txtB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtA"
android:text="B"
android:tag="B"
android:clickable="true"
android:layout_marginTop="83dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="visible"
android:textSize="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="switch"
android:id="#+id/btn1"
android:onClick="onClickButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Java Code :
public class MainActivity extends Activity {
TextView txtA,txtB;
boolean _isOnTxtA;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtA = (TextView)findViewById(R.id.txtA);
txtB = (TextView)findViewById(R.id.txtB);
btn1 = (Button)findViewById(R.id.btn1);
}
public void onClickButton(View v)
{
float mPos1x,mPos1y,mPos2x,mPos2y;
mPos1x = txtB.getX();
mPos1y = txtB.getY();
mPos2x = txtA.getX();
mPos2y= txtA.getY();
if(_isOnTxtA)
{
txtB.setX(mPos2x);
txtB.setY(mPos2y);
txtA.setX(mPos1x);
txtA.setY(mPos1y);
_isOnTxtA = false;
}
else
{
txtB.setX(mPos2x);
txtB.setY(mPos2y);
txtA.setX(mPos1x);
txtA.setY(mPos1y);
_isOnTxtA= true;
}
}
}
View.bringToFront method may be useful.
Where your layout is like:
<LinearLayout>
<TextView A>
<TextView B>
</LinearLayout>
To call bringToFront on TextView A will bring it front (the last position in the parent LinearLayout).
<LinearLayout>
<TextView B>
<TextView A>
</LinearLayout>
For more detailed example, below is layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/text_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/text_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_a" />
<TextView
android:id="#+id/text_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_b" />
</LinearLayout>
In your OnClickListener (in your Activity) call:
View textViewA = findViewById(R.id.text_a);
textViewA.bringToFront();
This should work.
Toggling behavior can be achieved by this application. For example:
ViewGroup textHolder = (ViewGroup) findViewById(R.id.text_holder);
textHolder.getChildAt(0).bringToFront();
ViewGroup.getChildAt(0) always returns the first child of the ViewGroup. So everytime you call bringToFront on the first child will be bring to front.
All previous answers do not work because you use a relative layout where a linear layout will suffice.
If you have to go RelativeLayout, do the following in your click listener
TextView textA = (TextView) findViewById(R.id.txtA);
TextView textB = (TextView) findViewById(R.id.txtB);
RelativeLayout.LayoutParams textALayoutParams = (RelativeLayout.LayoutParams) textA.getLayoutParams();
textALayoutParams.addRule(RelativeLayout.BELOW, R.id.txtB);
textA.setLayoutParams(textALayoutParams);
RelativeLayout.LayoutParams textBLayoutParams = (RelativeLayout.LayoutParams) textB.getLayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
textBLayoutParams.removeRule(RelativeLayout.BELOW);
} else {
textBLayoutParams.addRule(RelativeLayout.BELOW,0);
}
textB.setLayoutParams(textBLayoutParams);
This will place A under B. You can do the same for reversing.
I've got an empty ListView which has to contain another n different ListViews, depending on how many Markers are present inside a Cluster in a GoogleMaps activity when i tap on one Cluster on the screen, but I get nullPointerException when adding one of this inner ListViews to the main one. The two logs are showing correct data. Here's the code:
java code
public class myClusterInfoWindow implements GoogleMap.InfoWindowAdapter {
private View clusterView;
public myClusterInfoWindow () {
clusterView = getLayoutInflater().inflate(R.layout.cluster_info_window, null);
}
#Override
public View getInfoWindow(Marker marker) {
LinearLayout ll = (LinearLayout) findViewById(R.id.clusterll);
for (myClusterItem item : clickedCluster.getItems()) {
View portalView = getLayoutInflater().inflate(R.layout.portal_info_window, ll, true);
TextView title = (TextView) portalView.findViewById(R.id.name);
TextView hacks = (TextView) portalView.findViewById(R.id.hacks);
title.setText(item.getName());
hacks.setText(item.getHacks());
Log.d("CLUSTER", (String) title.getText());
Log.d("CLUSTER", (String) hacks.getText());
ll.addView(portalView); // TODO nullPointerException
}
return clusterView;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
}
cluster_info_window.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/clusterll">
</LinearLayout>
portal_info_window.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/wallet_bright_foreground_holo_light"
android:layout_marginBottom="5dp"
android:id="#+id/linearLayout">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" />
<TextView
android:id="#+id/hacks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"/>
</LinearLayout>
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="#+id/toggleButton"
android:layout_gravity="left|center_vertical"
android:layout_toRightOf="#+id/linearLayout"
android:background="#color/wallet_bright_foreground_holo_light"
android:layout_toEndOf="#+id/linearLayout"
android:layout_alignBottom="#+id/linearLayout"
android:layout_alignParentTop="true" />
</RelativeLayout>
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I've been looking at many examples of getting the pointers to the displays in the onCreate function but every time I do this I get null returns from my findViewById functions but if I do it elsewhere it works just fine. What am I missing to get this to work right?
Thanks for any help I must be missing something
EditText messageField;
AutoCompleteTextView numberField;
EditText countField;
TextView messageDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
sms = SmsManager.getDefault();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
messageField = (EditText) findViewById(R.id.message);
numberField = (AutoCompleteTextView) findViewById(R.id.number);
countField = (EditText) findViewById(R.id.count);
messageDisplay = (TextView) findViewById(R.id.display_message);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#000000"
tools:context="com.example.last.MainActivity$PlaceholderFragment" >
<AutoCompleteTextView
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/send"
android:layout_marginTop="49dp"
android:textColor="#android:color/white"
android:inputType="numberSigned"
android:selectAllOnFocus="true"
android:ems="10"
android:text="#string/phone_number" >
<requestFocus />
</AutoCompleteTextView>
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/message"
android:layout_marginRight="25dp"
android:layout_marginTop="70dp"
android:onClick="sendMessage"
android:textColor="#android:color/white"
android:text="#string/send_button" />
<EditText
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/send"
android:layout_below="#+id/number"
android:layout_marginTop="61dp"
android:ems="10"
android:inputType="textMultiLine"
android:textColor="#android:color/white"
android:selectAllOnFocus="true"
android:text="#string/default_message" />
<EditText
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/message"
android:layout_marginTop="32dp"
android:ems="4"
android:maxEms="4"
android:inputType="numberSigned"
android:textColor="#android:color/white"
android:text="#string/default_count" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/message"
android:layout_below="#+id/send" />
<TextView
android:id="#+id/display_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/progressBar1"
android:layout_below="#+id/progressBar1"
android:layout_marginTop="45dp"
android:layout_toLeftOf="#+id/send"
android:textColor="#android:color/white"
android:text="#string/default_display_message" />
<TextView
android:id="#+id/char_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/message"
android:layout_alignBottom="#+id/message"
android:layout_alignParentRight="true"
android:text="18/160" />
<android.gesture.GestureOverlayView
android:id="#+id/easter_egg_gesture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/display_message" >
</android.gesture.GestureOverlayView>
<Button
android:id="#+id/eeb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/easter_egg_gesture"
android:layout_alignParentLeft="true"
android:background="#000000"
android:onClick="easterEgg" />
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.joebot.MainActivity"
tools:ignore="MergeRootFrame" />
From your code, looks like your components like EdiText and TextView are residing in Fragment_main.xml but you are referencing them in Activity_main.xml.
Change your initialization of components to correct layout.
You are trying to reference Views in your Fragment's layout from your Activity. This is not possible as the Views reside in the Fragment's layout and not the Activity's one which is where it tries to look. You should define these Views in the Fragment that they are in and then expose them through methods if you desire access from your Activity.
You should however not make that decision lightly as it is recommended to keep Fragment details in your Fragments and only expose what you need to outside of that. Such as results or values instead of whole Views.
public MyFragment extends Fragment implements View.OnClickListener
{
private Button myButton;
private EditText myEditText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_input_submit, container, false);
myButton = (Button) view.findViewById(R.id.myButton);
myEditText = (EditText) view.findViewById(R.id.myEditText);
myButton.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v)
{
// keep the Fragment interaction in the Fragment
switch (v.getId())
{
case R.id.myButton:
Log.v("example fragment", "myButton was pressed");
break;
default:
break;
}
}
public EditText getMyEditText()
{
// you could get the EditText to use in your Activity
return this.myEditText;
}
public String getEditTextContents()
{
// or you could just allow access the data
return this.myEditText.getText().toString();
}
}
To make use of this you will need to keep a reference to your Fragment in your Activity:
public MyActivity extends FragmentActivity
{
private MyFragment myFragment;
#Override
public void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.activity_main);
myFragment = new MyFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, myFragment).commit();
}
...
}
Then to get access to the Fragment's information you would call either:
EditText myEditText = myFragment.getMyEditText();
or
String editTextContents = myFragment.getEditTextContents();
depending on your choice.
You can also communicate from the Fragment to the Activity using Interfaces. See this previous answer I made to a related question here for details on that and more examples of this.
The problem is, the following four lines of code:
messageField = (EditText) findViewById(R.id.message);
numberField = (AutoCompleteTextView) findViewById(R.id.number);
countField = (EditText) findViewById(R.id.count);
messageDisplay = (TextView) findViewById(R.id.display_message);
These lines should come AFTER your fragment transaction:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
getFragmentManager().executePendingTransactions();
}
messageField = (EditText) findViewById(R.id.message);
numberField = (AutoCompleteTextView) findViewById(R.id.number);
countField = (EditText) findViewById(R.id.count);
messageDisplay = (TextView) findViewById(R.id.display_message);
This should work.
Note also that I've added the executePendingTransactions() method to your code (it is required in this case). However, I'd prefer to handle those Views in the Fragment (unless there's a good reason to use them in the Activity itself). Remove these lines from the onCreate() method of your Activity and add them to the onViewCreated() method of your PlaceholderFragment :
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
messageField = (EditText) view.findViewById(R.id.message);
numberField = (AutoCompleteTextView) view.findViewById(R.id.number);
countField = (EditText) view.findViewById(R.id.count);
messageDisplay = (TextView) view.findViewById(R.id.display_message);
}
Whatever you would like to do with those Views can be done in this method. Hope this helps ... :)
I just used created by first Dialog using DialogFragment.
Everything works great except I can't get the Dialog to wrap it's layout.
My layout has the height of all elements to wrap_content.
In MyFragmentDialog I can't even find a method that would imply that it can be used to set the height of the FragmentDialog. What am I missing? How do I make a DialogFragment fit it's content?
The DialogFrament's onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Set title for this dialog
getDialog().setTitle("Backup & Restore");
getDialog().setCancelable(true);
View v = inflater.inflate(R.layout.backup_restore, container, false);
TextView msg = (TextView) v.findViewById(R.id.br_label_message);
msg.setText("Backups are placed in the Downloads Directory:\n" + BACKUP_PATH.getAbsolutePath());
// TextView files_label = (TextView) v.findViewById(R.id.label_restore);
Spinner files = (Spinner) v.findViewById(R.id.br_restore_file);
if (BACKUP_PATH.exists()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
return filename.contains(FTYPE) || sel.isDirectory();
}
};
mFileList = BACKUP_PATH.list(filter);
} else {
mFileList = new String[0];
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item, mFileList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
files.setAdapter(adapter);
files.setOnItemSelectedListener(this);
Button backup = (Button) v.findViewById(R.id.br_backup_btn);
Button restore = (Button) v.findViewById(R.id.br_restore_btn);
Button cancel = (Button) v.findViewById(R.id.br_cancel_btn);
backup.setOnClickListener(this);
restore.setOnClickListener(this);
cancel.setOnClickListener(this);
return v;
}
This is the layout:
<?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="wrap_content"
android:orientation="vertical"
android:padding="8dp" >
<TextView
android:id="#+id/br_label_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="8dp"
android:text=""
android:textSize="14sp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/br_tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/br_label_restore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="8dp"
android:text="Restore file"
android:textSize="14sp" />
<Spinner
android:id="#+id/br_restore_file"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow>
<Button
android:id="#+id/br_restore_btn"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="Restore"
android:textSize="14sp" />
<Button
android:id="#+id/br_backup_btn"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:text="Backup"
android:textSize="14sp" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/br_cancel_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel"
android:textSize="14sp" />
</LinearLayout>
Thanks,
It turns out to be an issue with LinearLayout despite setting a height on it, in DialogFragment it seems to be taking more space than I want it to. I switched layout to be a RelativeLayout the content Dialog seems to resize to fit the content.
You can make it work with all kind of layout in adding the size of the layout in the onResume of your dialogFragment :
#Override
public void onResume()
{
super.onResume();
Window window = getDialog().getWindow();
window.setLayout(300, 300);
window.setGravity(Gravity.CENTER);
}
I took a leap into the Dialog api so I am certainly not sure but you could try to call getWindow on the dialog and then call setLayout(width, height)
getDialog().getWindow().setLayout(300,300);
I don't see the top portion of your LinearLayout tag, but I've seen cases where all that was needed was the
android:orientation="vertical"
XML attribute. It can cause a headache but is fortunately easy to fix.