This question already has answers here:
Fragment won't launch
(2 answers)
Closed 5 years ago.
I am pretty new to android development, so please don't flame me for stupid questions/mistakes!
I have a listview inside my activity, but i want to open up a fragment when a frame in the listview is clicked on. I have the onclick working, but it is not launching the new activity.
I'll include my code below.
This is the oncreate
protected void onCreate (Bundle savedInstanceState)
{
//Fragment fragment_blank2=new SomeFragment();
e = myBadData.getData();
super.onCreate(savedInstanceState);
setContentView(R.layout.event_list);
events=(ListView) findViewById(R.id.dayList);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,e);
events.setAdapter(adapter);
events.setOnItemClickListener(this);
}
this is the onclick
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
myBadData.setId(i);
Fragment fr = new event_description();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.eventdescription, fr);
}
this is the XML of the fragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id = "#+id/eventdescription"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="137dp"
android:text="#string/event_name"
android:textSize="26sp"
android:layout_gravity="top"
android:gravity="top|center"
android:paddingTop="10dp"
android:id="#+id/textView"
android:background="#android:color/holo_orange_light"
android:textColor="#android:color/black"
android:layout_weight="1.08" />
<TextView
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:layout_marginTop="#dimen/activity_top_margin"
android:layout_marginLeft="#dimen/activity_side_margin"
android:textSize="18sp"
android:drawableTint="#android:color/background_dark" />
<TextView
android:text="#string/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/time"
android:layout_marginTop="70dp"
android:layout_marginLeft="#dimen/activity_side_margin"
android:textSize="18sp" />
<TextView
android:text="#string/cost"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cost"
android:layout_marginTop="#dimen/activity_top_margin"
android:layout_marginRight="70dp"
android:textSize="18sp"/>
<TextView
android:text="#string/address"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/address"
android:layout_marginTop="70dp"
android:layout_marginRight="60dp"
android:textSize="18sp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="135dp"
android:layout_marginLeft="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:id="#+id/tv_long"
android:paddingTop="10dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/sample_text"
android:textSize="18sp"
android:layout_weight="1.08">
</TextView>
</LinearLayout>
</ScrollView>
<Button
android:text="#string/add_to_calendar"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/button2"
android:layout_gravity="center_horizontal"
android:layout_marginTop="95dp"/>
</FrameLayout>
here is the class of the fragment
public class event_description extends Fragment
{
#Nullable
//#Override
public View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate (R.layout.event_description, container, false);
Bundle args = getArguments();
String arg = args.getString(eventList.KEY_NAME);
//return super.(R.layout.event_description, container, false);
return view;
}
public View getView() {
return getView();
}
}
For Your Activity XML
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/my_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/dayList"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</FrameLayout>
And Pass Activity's Container in FramgmentTransaction
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l)
{
myBadData.setId(i);
Fragment fr = new event_description();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
//Your Container of Activity
fragmentTransaction.add(R.id.my_frame, fr);
fragmentTransaction.commit();
}
and Don't forgot to commint it.
No need to use framgment's FrameLayout as a container..
Related
Hi I have a scenario like I have a created a Main Activity and different fragments. MainActivity I am implemented the bottom navigation bar it contains different tabs
1.Task
2.Account
3.Contact
For the above have created the different fragments above tabs we have a common button called '+'.
Now My problem is that if i opened the account fragment want to display the fragment details .In that account tab has common '+' button for all .If I click on + button want to create a new account fragment.
How to resolve it.
MainActivity:
public void initBottomNavigationItems() {
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.task:
toolbar.setTitle("Task");
fragment = new TaskFragement();
loadFragment(fragment);
return true;
case R.id.account:
toolbar.setTitle("Account");
fragment = new AccountFragement();
loadFragment(fragment);
return true;
case R.id.contact:
toolbar.setTitle("Contact");
fragment = new ContactFragment();
loadFragment(fragment);
return true;
case R.id.opportunity:
toolbar.setTitle("Opportunity");
fragment = new OpportuntityFragement();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
If click on account tab it will move to the account fragment .In the same way want if i click on fab button want to replace account fragment with create fragment .But my fab button is in activity_main not in account fragement.
AccountFragement:
public class AccountFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_account, container, false);
}
}
fragment_account.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
android:background="#color/White">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/slivergray"
app:cardCornerRadius="8dp"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/White">
<ImageView
android:id="#+id/appImage"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginLeft="16dp"
android:background="#drawable/ic_account_circle_black_24dp"
android:backgroundTint="#color/gray"
android:scaleType="centerCrop"
tools:ignore="ContentDescription"/>
<TextView
android:id="#+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/appImage"
android:paddingLeft="16sp"
android:paddingRight="16dp"
android:text="Apollo Hospital"
android:textColor="#color/black"
android:textSize="18sp"
tools:ignore="RtlHardcoded"/>
<TextView
android:id="#+id/subHeaderText"
style="#style/Base.TextAppearance.AppCompat.Subhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/headingText"
android:layout_toRightOf="#+id/appImage"
android:paddingLeft="16dp"
android:text="Hospital"
android:paddingRight="16dp"
android:textColor="#color/gray"
android:textSize="15sp"/>
<TextView
android:id="#+id/subHeadingText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/subHeaderText"
android:layout_toRightOf="#+id/appImage"
android:gravity="left"
android:lines="5"
android:maxLines="5"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:text="stories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detailstories_detail"
android:textColor="#color/gray"
android:textSize="14sp"/>
<TextView
android:id="#+id/textViewOptions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="⋮"
android:textColor="#color/gray"
android:layout_marginRight="10dp"
android:textAppearance="?android:textAppearanceLarge"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/subHeadingText">
<LinearLayout
android:layout_width="209dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginLeft="30dp"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:backgroundTint="#color/gray"
android:src="#drawable/ic_account_circle_black_24dp"></ImageView>
<Button
android:id="#+id/action1"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Action 1"
android:textColor="#color/gray"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="right">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:src="#drawable/ic_account_circle_black_24dp"
android:layout_marginLeft="50dp"></ImageView>
<Button
android:id="#+id/action2"
style="#style/Base.Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Action 2"
android:textColor="#color/gray"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</RelativeLayout>
I understand that you want to call your activity method from fragment.(from a + button in fragment).
Then you can use an interface in your fragment to get callback in activity.
public class AccountFragment extends Fragment {
OnFabClickListener listener;
// Container Activity must implement this interface
public interface OnFabClickListener{
public void onCreateNewAccount();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener= (OnFabClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFabClickListener");
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onCreateNewAccount();
}
});
}
...
}
Then in your activity implement the interface this way.
public class MainActivity extends AppCompatActivity implements OnFabClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
}
#Override
public void onCreateNewAccount() {
//Add your new account creation code here like loadFragment
}
}
I'm trying to create validations in some edittext and I am using an example I found on the internet but when I implemented the code my findViewById is in error (in view can not be applied to android.view.view.
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_cadastro_contas_bancarias, container, false);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = null;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (v.getId()) {
case R.id.btn_cadastrar_conta:
registerAttemptWithRetrofit(1,
"3948",
"0",
"01089842",
"3",
1);
fragment = new ContasBancarias();
default:
break;
}
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
View view1 = inflater.inflate(R.layout.fragment_cadastro_contas_bancarias, container, false);
EditText agencia = (EditText) getView().findViewById(R.id.txt_agencia);
if ("".equals(agencia.getText().toString().trim())) {
Toast.makeText(getActivity(), "Campo Obrigatório", Toast.LENGTH_SHORT).show();
return;
//
}
}
};
return view; }
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:text="Dados Bancários"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_marginTop="16dp"
android:textSize="18sp"
android:textColor="#android:color/black"
android:textColorHighlight="#color/Black"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/txt_agencia"
android:hint="Agência"
android:layout_alignBaseline="#+id/txt_digito_agencia"
android:layout_alignBottom="#+id/txt_digito_agencia"
android:layout_toEndOf="#+id/spn_tipo_de_conta"/>
<EditText
android:layout_width="95dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/txt_digito_conta"
android:layout_alignBottom="#+id/txt_conta"
android:layout_toEndOf="#+id/txt_conta"
android:layout_alignTop="#+id/txt_conta"
android:hint="Digito"
android:textStyle="bold" />
<Spinner
android:layout_width="150dp"
android:layout_height="40dp"
android:id="#+id/spn_tipo_de_conta"
android:layout_below="#+id/textView3"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />
<Button
android:text="Cancelar"
android:layout_width="90dp"
android:layout_height="40dp"
android:id="#+id/btn_cancelar"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="21dp"
android:background="#color/DefaultBlue"
android:textColor="#android:color/white"
android:textStyle="normal|bold"
android:onClick="cancelar (CadastroContasBancarias)" />
<Button
android:text="Cadastrar"
android:layout_width="90dp"
android:layout_height="40dp"
android:id="#+id/btn_cadastrar_conta"
android:background="#color/DefaultBlue"
android:textColor="#android:color/white"
android:textStyle="normal|bold"
android:layout_alignBaseline="#+id/btn_cancelar"
android:layout_alignBottom="#+id/btn_cancelar"
android:layout`enter code here`_alignParentEnd="true" />
</RelativeLayout>
You can try this you get the solutions....
View view1 = inflater.inflate(R.layout.fragment_cadastro_contas_bancarias, container, false);
EditText agencia = (EditText) view1 ().findViewById(R.id.txt_agencia);
I am new to android developing and I am currently stumped at this situation.
Is there a way to change a particular child view of a fragment?
For example, I have a TextView and Button in a Fragment. Now after inflating this fragment and committing it, I would like to only change the text of the TextView based on the user input.
EDIT: The same layout is used to create multiple fragments. I would like to just change the TextView of a particular Fragment.
MainActivity Code:
public class MainActivity extends Activity {
Button bt;
EditText et;
LinearLayout ly;
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button) findViewById(R.id.badd);
ly=(LinearLayout) findViewById(R.id.lay_ver);
et=(EditText) findViewById(R.id.etadd);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// multiple fragments are created
MyFragment f=new MyFragment();
FragmentManager fm=getFragmentManager();
FragmentTransaction t=fm.beginTransaction();
t.add(R.id.sv1, f, "hi");
t.commit();
et.setText("");
}
});
//would like to change the text of the textview of the fragment
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Fragment Code:
public class MyFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.frag_lay, null);
return v;
}
}
activity_main XML :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/lay_ver"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/lay_hor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/etadd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="80"
android:hint="Enter Subject"
android:paddingTop="20dp" />
<Button
android:id="#+id/badd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20"
android:text="Add" />
</LinearLayout>
<ScrollView
android:id="#+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/sv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layfrag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.53"
android:text="HiHow"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.20"
android:text="Hello"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
You can add a list of Fragments in your activity and each fragment to the list when you create them. Then you can get the fragment you want to change and do as cdblades said :
View parent = fragment.getView();
View childTextView = (TextView)parent.findViewById(R.id.myChildTextView);
But why are you adding the fragments in the same container?
The base View class has the findById() method that you can use to get a reference to child views like so:
View parent = fragment.getView();
View childTextView = (TextView)parent.findViewById(R.id.myChildTextView);
Aim:
Create a activity that have two buttons, button 1 and button 2. When click, the fragment will alternate between the two fragments.
Background:
Fragmentone will take the edittext from the main activity and settext on the textview on the fragment.
Fragmenttwo will take display text to the tablelayout. (My ultimate goal is to use the input from the main activty and display it to one of the textview of the table, but it is not working, kindly advise on that)##issue 1
Problems:
The button1 that is supposed to display fragmentone is not working. After keying in the input into the edittext on the mainactivity, when i click the button, the fragmenttwo persist. FragmentOne did not come out. Place an toast in fragmentone and the toast display my input.
Special Thanks to:
Would like to extend a special thanks to helpful people in this community for guiding me this far. And will like to extend my thanks to Raghunandan who guide me through fragment advance I, II. Thanks you very much for assisting me through my learning journey. Hope my questions and raghunandan advice would help reduce the learning curve for those embraking on this journey.
Fragment Intermediate (I)
Fragment Intermediate(I):Getting input from edittext, set text in textview of a fragment
Fragment Intermediate (II)
Fragment Intermediate (II):Dynmically adding row in a fragment, Android
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectFrag(View view) {
Fragment fr;
if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}
else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Input" />
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</TableRow>
<TableRow
android:id="#+id/tableRow9"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Button2" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Calculate" />
</TableRow>
</TableLayout>
</FrameLayout>
<fragment
android:name="com.example.sample.FragmentTwo"
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
FragmentOne.java
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
TextView warcraft= (TextView) view.findViewById(R.id.moargold);
EditText moargold = (EditText) getActivity().findViewById(R.id.input);
Double vespenegas = Double.parseDouble(moargold.getText().toString());
warcraft.setText(new Double(vespenegas).toString());
Toast toast = Toast.makeText(getActivity(),new Double(vespenegas).toString() , Toast.LENGTH_SHORT);
toast.show();
return view;
}
}
fragment_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gold Count:" />
<TextView
android:id="#+id/moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_two, container, false);
EditText input = (EditText) getActivity().findViewById(R.id.input);
TableLayout tl=(TableLayout) view.findViewById(R.id.mainLayout);
TableRow tr = new TableRow(getActivity());
tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview1 = new TextView(getActivity());
textview1.setText("happy");
tr.addView(textview1);
TextView textview2 = new TextView(getActivity());
textview2.setText("unhappy");
//###############To insert text from editview to table
// Double buygas = Double.parseDouble(input.getText().toString());
// textview2.setText(new Double(buygas).toString());
tr.addView(textview2);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
return view;
}
}
fragment_two.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="vertical"
android:background="#ffff00">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainLayout">
<TableRow
android:id="#+id/infoRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="First"
android:id="#+id/column1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:text="Second"
android:id="#+id/column2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</TableRow>
</TableLayout>
</LinearLayout>
Just have the FrameLayout and EditText in activity_main.xml. FrameLayout is a container (ViewGroup) to which you add or replace fragments. Your TableLayout can be in fragment layout.
You are adding/replacing fragment programatically so what is the need to have the same in xml.
Have this in activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10" >
<requestFocus />
</EditText>
<FrameLayout
android:id="#+id/container" // id is container
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/button1"
android:layout_below="#+id/input"
>
</FrameLayout>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/input"
android:onClick="selectFrag"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:onClick="selectFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/input"
android:layout_alignParentBottom="true"
android:text="Button2" />
</RelativeLayout>
Then in MainActivity
public class MainActivity extends Activity {
Fragment fr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectFrag(View view) {
if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}
else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.container, fr);
fragmentTransaction.commit();
}
}
FragmentOne
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.frag1, container, false);
TextView warcraft= (TextView) view.findViewById(R.id.moargold);
EditText moargold = (EditText) getActivity().findViewById(R.id.input);
Double vespenegas = Double.parseDouble(moargold.getText().toString());
warcraft.setText(String.valueOf(vespenegas));
Toast toast = Toast.makeText(getActivity(),String.valueOf(vespenegas) , Toast.LENGTH_SHORT);
toast.show();
return view;
}
}
frag1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gold Count:" />
<TextView
android:id="#+id/moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
FragmentTwo
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.frag2, container, false);
EditText input = (EditText) getActivity().findViewById(R.id.input);
TableLayout tl=(TableLayout) view.findViewById(R.id.TableLayout01);
TableRow tr = new TableRow(getActivity());
tr.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview1 = new TextView(getActivity());
textview1.setText("happy");
tr.addView(textview1);
TextView textview2 = new TextView(getActivity());
textview2.setText("unhappy");
//###############To insert text from editview to table
// Double buygas = Double.parseDouble(input.getText().toString());
// textview2.setText(new Double(buygas).toString());
tr.addView(textview2);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
return view;
}
}
frag2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/dis_moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gold Count:" />
<TextView
android:id="#+id/moargold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
Snap
While you add your Fragments dynamically, you keep your FragmentTwo inside your layout. Try to remove this in your layout:
<fragment
android:name="com.example.sample.FragmentTwo"
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Also, in your code, you add dynamically a Fragment and with replace method, you set the container as id fragment_place:
fragmentTransaction.replace(R.id.fragment_place, fr);
However, this id is using by your fragment (FragmentTwo, the first piece of code above) and you cannot replace a fragment which is not added dynamically. You need to host your fragment inside a FrameLayout but yours has no id, try to add this:
<FrameLayout
android:id="#+id/fragment_place" /// this line to create and id
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
Then, you will be able to host, add and replace your fragments into your framelayout as you want.
New android developer here. I am trying to create a dynamic UI that loads based on the users selection of a RadioGroup. Based on their selection, one of 3 possible fragments will be loaded into a LinearLayout section. This is my first attempt at my own sample problem that is not just a walk-through tutorial. Here is the main activity:
public class BaseConverter extends Activity {
RadioGroup convert;
Fragment toFragment;
RadioGroup toRadioGroup = null;
TextView inputDisplay = null;
TextView outputDisplay = null;
TextView resultTitle = null;
#Override
public void onCreate(Bundle sIS) {
super.onCreate(sIS);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.base_converter);
convert = (RadioGroup) this.findViewById(R.id.bc_convert_group);
convert.setOnCheckedChangeListener(new ConvertListener());
FragmentManager fm = getFragmentManager();
FragmentTransaction converterFragment = fm.beginTransaction();
ConvertEmptyFragment emptyTo = new ConvertEmptyFragment();
converterFragment.replace(R.id.bc_converter_fragment, emptyTo);
converterFragment.commit();
FragmentTransaction toFragment = fm.beginTransaction();
ConvertEmptyFragment emptyConverter = new ConvertEmptyFragment();
toFragment.replace(R.id.bc_to_fragment, emptyConverter);
toFragment.commit();
}
#Override
public void onResume() {
convert.clearCheck();
super.onResume();
}
#Override
public void onPause() {
convert.clearCheck();
super.onPause();
}
// I put a little null check so you can see how I'm trying to access the TextViews and what results
public void updateUIComponents(){
View converterView = this.findViewById(R.id.bc_converter_fragment);
inputDisplay = (TextView)converterView.findViewById(R.id.bc_display_input);
outputDisplay = (TextView)converterView.findViewById(R.id.bc_display_output);
if (inputDisplay == null){
Log.d("BaseConverter", "inputDisplay == null");
} else {
Log.d("BaseConverter", "inputDisplay != null");
}
}
class ConvertListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Fragment toFragment;
Fragment converterFragment;
switch (checkedId) {
case R.id.bc_convert_binary:
toFragment = new ConvertRBFragmentBinary();
converterFragment = new ConverterFragmentBinary();
break;
case R.id.bc_convert_decimal:
toFragment = new ConvertRBFragmentDecimal();
converterFragment = new ConverterFragmentDecimal();
break;
case R.id.bc_convert_hex:
toFragment = new ConvertRBFragmentHex();
converterFragment = new ConverterFragmentHex();
break;
default:
toFragment = new ConvertEmptyFragment();
converterFragment = new ConvertEmptyFragment();
break;
}
FragmentManager fm = getFragmentManager();
FragmentTransaction converterTransaction = fm.beginTransaction();
converterTransaction.replace(R.id.bc_converter_fragment, converterFragment);
converterTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
converterTransaction.commit();
FragmentTransaction toTransaction = fm.beginTransaction();
toTransaction.replace(R.id.bc_to_fragment, toFragment);
toTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
toTransaction.commit();
updateUIComponents();
}
}
So, based on what a user chooses, the proper fragments will be loaded into the respective LinearLayout sections. However, now I want to implement the business logic of the fragments (which is just integer base conversion; i.e. binary number to decimal...) but when I try to access the TextViews, as seen in the updateUIComponents method, I get null pointers. What am I missing?
Here's the ConverterFragmentBinary class for reference:
public class ConverterFragmentBinary extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sIS){
View v = inflater.inflate(R.layout.converter_fragment_binary, container, false);
return v;
}
}
and its respective xml layout for reference:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/bc_binary_converter_logo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:maxHeight="30dip"
android:src="#drawable/binary_converter" />
<TextView
android:id="#+id/bc_display_input"
style="#style/input_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical|right"
android:lines="1"
android:minHeight="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF000000"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/button_num_0"
style="#style/op_button_land"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:gravity="center"
android:onClick="num0"
android:text="#string/num_0" />
<Button
android:id="#+id/button_num_1"
style="#style/op_button_land"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:gravity="center"
android:onClick="num1"
android:text="#string/num_1" />
</LinearLayout>
<TextView
android:id="#+id/bc_result_title"
style="#style/radio_button_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_marginTop="10dip"
android:gravity="left"
android:text="#string/choose_convert" />
<TextView
android:id="#+id/bc_display_output"
style="#style/display_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:layout_marginTop="5dip"
android:gravity="center_vertical|right"
android:lines="1"
android:minHeight="30sp" />
</LinearLayout>
and then heres the main activity it gets loaded into:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/base_conversion_layout"
style="#style/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="5"
android:baselineAligned="false"
android:gravity="center_vertical|left"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="vertical" >
<TextView
style="#style/radio_button_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convert" />
<RadioGroup
android:id="#+id/bc_convert_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dip" >
<RadioButton
android:id="#+id/bc_convert_binary"
style="#style/radio_button"
android:text="#string/binary" />
<RadioButton
android:id="#+id/bc_convert_decimal"
style="#style/radio_button"
android:text="#string/decimal" />
<RadioButton
android:id="#+id/bc_convert_hex"
style="#style/radio_button"
android:text="#string/hex" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="#+id/bc_to_fragment"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="3"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/bc_converter_fragment"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="13"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
Thanks in advance and sorry for the long code blocks but I figured it was better to include more than less.
Also, you should inflate your Fragments layout to bring it from your XML to your Java code instead of simply referring it using findViewById() method.
So instead of doing this,
View converterView = this.findViewById(R.id.bc_converter_fragment);
Do this inside your onCreateView method of the fragment,
View converterView = infalter.inflate(R.id.bc_converter_fragment,null);
updateUIComponents(converterView);//call this methid and pass your view
new method looks like this,
public void updateUIComponents(View converterView){
inputDisplay = (TextView)converterView.findViewById(R.id.bc_display_input);
outputDisplay = (TextView)converterView.findViewById(R.id.bc_display_output);
if (inputDisplay == null){
Log.d("BaseConverter", "inputDisplay == null");
} else {
Log.d("BaseConverter", "inputDisplay != null");
}
}