Display layout in fragment on main activity xamarin - android

I am not able to display layout on class SecondFragment : Fragment
MAIN ACTIVITY
$ [Activity (Label = "project", Theme = "#style/Tab")]
public class TabActivity : Activity
{
ProductDB dbHelper;
ICursor cursor;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.MainTab);
dbHelper = new ProductDB(this);
cursor = dbHelper.ReadableDatabase.RawQuery ("select * from movie", null);
StartManagingCursor (cursor);
this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
AddTab ("Products", new FirstFragment(this, cursor));
AddTab ("User Profile", new SecondFragment());
AddTab("User Order", new ThirdFragment());
if (savedInstanceState != null)
this.ActionBar.SelectTab(this.ActionBar.GetTabAt(savedInstanceState.GetInt("tab")));
}
void AddTab (string tabText, Fragment view)
{
var tab = this.ActionBar.NewTab ();
tab.SetText (tabText);
tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs ab)
{
var fragment = this.FragmentManager.FindFragmentById(Resource.Id.frameLayout1);
if (fragment != null)
ab.FragmentTransaction.Remove(fragment);
ab.FragmentTransaction.Add (Resource.Id.frameLayout1, view); };
tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs ab) {
ab.FragmentTransaction.Remove(view); };
this.ActionBar.AddTab (tab);
}
protected override void OnDestroy ()
{
StopManagingCursor (cursor);
cursor.Close ();
base.OnDestroy ();
}
class FirstFragment: Fragment
{
ICursor cursor;
ListView listView;
Activity context;
public FirstFragment(Activity context, ICursor cursor) {
this.cursor = cursor;
this.context = context;
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
var view = inflater.Inflate (Resource.Layout.Tab1, container, false);
listView = view.FindViewById<ListView> (Resource.Id.mylist);
listView.Adapter = new ProductAdapter (context, cursor);
listView.ItemClick += OnItemListClick;
return view;
}
protected void OnItemListClick (object sender, AdapterView.ItemClickEventArgs ab)
{
var curs = (ICursor)listView.Adapter.GetItem (ab.Position);
var movieName = curs.GetString (1);
Android.Widget.Toast.MakeText (context, movieName, Android.Widget.ToastLength.Short).Show();
}
}
class SecondFragment : Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(R.layout.your_fragment, container, false);
return view;
}
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.article_view, container, false);
// base.OnCreateView(inflater, container, savedInstanceState);
// var view = inflater.Inflate(Resource.Layout.User, container, false);
// var layout = view.FindViewById<LinearLayout>(Resource.Id.linearLayoutmargin1);
// return view;
}
class ThirdFragment : Fragment

After observing above code, there might be some issue in onCreateView of SecondFragment, you missed below line,
base.OnCreateView (inflater, container, savedInstanceState);
Confirm and let me know whether working or not?
:)GlbMP

Related

Open a fragment from a fragment's fragment?

I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.

How to transfer the value to recylerview of one which is received from another fragment?

i have made two fragments in my app.
1st fragment (EditFrag) and 2nd fragment (ListTable). i want to transfer the value of 1st fragment(from EditText of 1st fragment) to the recyclerView of 2nd fragment.
how should i do that.....i can't find right documentation.
Thank you for your concern!
MainActivity:
public class MainActivity extends AppCompatActivity implements EditFrag.TransferValue{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListTable frag1=new ListTable();
FragmentManager manager=getSupportFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.table_value_container,frag1,"fragment");
transaction.commit();
EditFrag frag2=new EditFrag();
FragmentManager manager1=getSupportFragmentManager();
FragmentTransaction transaction1=manager1.beginTransaction();
transaction1.add(R.id.table_container,frag2,"fragment_edit");
transaction1.commit();
}
#Override
public void sendValue(String value) {
Log.d("ashu","button is pressed");
ListTable listTable = (ListTable) getSupportFragmentManager().findFragmentById(R.id.table_value_container);
listTable.receiveValue(value);
}
}
2nd fragment(ListTable):
public class ListTable extends Fragment {
public TextView myEditText1;
private RecyclerView recyclerView;
public ListTable() {
// Required empty public constructor
}
public static ListTable newInstance(String param1, String param2) {
ListTable fragment = new ListTable();
Bundle args = new Bundle();
Log.d("ashu", "new instance is called :");
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("ashu", "oncreata called by inflating: ");
View view = inflater.inflate(R.layout.fragment_list_table, container, false);
myEditText1 = (TextView) container.findViewById(R.id.table_value);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
MyAdapter a = new MyAdapter();
recyclerView.setAdapter(a);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void receiveValue(String value) {
myEditText1.setText(value);
}
public class MyAdapter extends RecyclerView.Adapter<MyDataViewHolder> {
#Override
public MyDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("ashu", "oncreateview holder of adapter ia called");
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_list_table, parent, false);
return new MyDataViewHolder(view);
}
#Override
public void onBindViewHolder(MyDataViewHolder holder, int position) {
holder.myEditText.setText("Table: " + position);
}
#Override
public int getItemCount() {
return 10;
}
}
public class MyDataViewHolder extends RecyclerView.ViewHolder {
public TextView myEditText;
public MyDataViewHolder(View itemView) {
super(itemView);
Log.d("ashu", "DAta view holder is called: ");
myEditText = (TextView) itemView.findViewById(R.id.table_value);
}
}
}
1st Fragment(EditFrag):
public class EditFrag extends Fragment {
TransferValue SendData;
EditText inputvalue;
Button click;
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.edit_frag_layout, container, false);
inputvalue = (EditText) view.findViewById(R.id.edit_text);
click = (Button) view.findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String received = inputvalue.getText().toString();
SendData.sendValue(received);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SendData = (TransferValue) context;
} catch (ClassCastException e) {
Log.d("ashu", "implement the methods");
throw new ClassCastException("implemented the methods");
}
}
public interface TransferValue {
public void sendValue(String value);
}
}
create the instance of fragment2 from where want to receive the value to:
public static Fragment2 createInstance(String data) {
Fragment2 fragment = new Fragment2();
Bundle bundle = new Bundle();
bundle.putString("keyword", data);
fragment.setArguments(bundle);
return fragment;
}
and the get the data as below:
Bundle bundle = getArguments();
if (bundle != null) {
String data = bundle.getString("data");
}
You can use bundle in an order to pass data to fragment:
Example:
// Set bundle as arguments to the fragment
Bundle bundle = new Bundle();
bundle.putString(MyKey1, MyValue1);
bundle.putString(MyKey2, MyValue2);
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
Inside onCreateView of fragment:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.repairer_part_details_fragment, container, false);
String value1 = getArguments().getString(MyKey1);
String value2 = getArguments().getString(MyKey2);
return view;
}
There are many ways to do that. I see your codes above, and 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.
The first solution: You can use this link using obserable pattern to communication 2 fragments.
The second solution: you can use EventBus lib for communication, it 's very simple

ListView in DialogFragment does not show up

I want to implement a button on my MainActivity which triggers a DialogFragment where ListView inside. When I click on the button in my MainActivity, DialogFragment does not show up. The development environment is Xamarin.Android. Here is my implementation:
MainActivity
namespace DialogExample
{
[Activity (Label = "DialogExample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
private Button mClickBtn;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
mClickBtn = FindViewById<Button> (Resource.Id.myButton);
mClickBtn.Click += MClickBtn_Click;
}
void MClickBtn_Click (object sender, EventArgs e)
{
FragmentTransaction transaction = FragmentManager.BeginTransaction ();
Dialog_Form dialogList = new Dialog_Form ();
dialogList.Show (transaction, "Dialog fragment");
}
}
}
Diaolog_Form
namespace DialogExample
{
public class Dialog_Form:DialogFragment
{
private ListView myListView;
private List<string> myList=new List<string> ();
public Dialog_Form ()
{
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
myList.Add ("Jason");
myList.Add ("Kenny");
myList.Add ("Tedd");
var view = inflater.Inflate (Resource.Layout.dialog_form, container, false);
myListView = view.FindViewById<ListView> (Resource.Id.myListView);
ArrayAdapter adapter = new ArrayAdapter (Activity, Android.Resource.Layout.SimpleListItem1, myList);
myListView.Adapter = adapter;
return view;
}
}
}

how to move to new fragment at on OnItemClickListener()

In my application I want to put a ListView in the first Fragment and I want to move to a new Fragment when I clicked on an item such that each item has its own details
in my code.
I implemented it to move to another Activity, but now my manager says it must go to another Fragment instead of other activity. I'm new to the Fragment world and I don't know how to do this. The manager says that I can use the list fragment but I have not found any useful code.
This my code:
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
static ProgressDialog pd ;
ViewPager mViewPager;
List<Fragment> fragments ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentThree.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFour.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFive.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentSix.class.getName()));
mSectionsPagerAdapter=new SectionsPagerAdapter(super.getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
pd = new ProgressDialog(this);
mViewPager.setAdapter(mSectionsPagerAdapter);
//
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int _pos = position % 6;
return fragments.get(_pos);
}
#Override
public int getCount() {
// Show 3 total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
final String title_section4="Section4";
final String title_section5="Section5";
final String title_section6="Section6";
final String title_section1="Section1";
final String title_section2="Section2";
final String title_section3="Section3";
Locale l = Locale.getDefault();
switch (position) {
case 0:
return title_section1.toUpperCase(l);
case 1:
return title_section2.toUpperCase(l);
case 2:
return title_section3.toUpperCase(l);
case 3:
return title_section4.toUpperCase(l);
case 4:
return title_section5.toUpperCase(l);
case 5:
return title_section6.toUpperCase(l);
}
return null;
}
}
public static class FragmentOne extends Fragment {
ArrayList< String > ar;
ArrayAdapter< String > ad ;
ListView lv ;
TextView tv;
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one, container, false);
tv = (TextView) rootView.findViewById(R.id.mywidget);
tv.setSelected(true);
ar = new ArrayList<String>();
lv = (ListView) rootView.findViewById(R.id.listView1);
for (int i = 0 ; i< 10 ; i++){
ar.add("My Item " + String.valueOf(i));
}
ad = new ArrayAdapter<String>
(getActivity().getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
ar);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast t = Toast.makeText(getActivity(), "Message",
Toast.LENGTH_SHORT);
t.show();
Intent i = new Intent(getActivity(), tst.class);
startActivity(i);
}
});
return rootView;
}
}
public static class FragmentTwo extends Fragment {
public FragmentTwo() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.two, container, false);
return rootView;
}
}
public static class FragmentThree extends Fragment {
public FragmentThree() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.three, container, false);
return rootView;
}
}
public static class FragmentFour extends Fragment {
public FragmentFour() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.four, container, false);
return rootView;
}
}
public static class FragmentFive extends Fragment {
public FragmentFive() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.five, container, false);
return rootView;
}
}
public static class FragmentSix extends Fragment {
public FragmentSix() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.six, container, false);
return rootView;
}
}
}
You have to replace the fragment using Transaction
See here:
http://developer.android.com/guide/components/fragments.html#Example
Check the showDetails(int index) method of TitlesFragment class:
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Use pager and give integer index to each fragment then use following code in itemclick
ViewPager pager;
pager.setCurrentItem(index, true);

ListFragment getListView is null

I am making a list that will be placed under another view.
Based on the other article, i should contain the other view in the header of the listview.
I am using ListFragment and will be attached to several activity. So I am creating a method to set the header of the ListFragment.
The problem is the getListView() method is returning null, although I call the addHeader after the list is shown.
Why is the the getListView() is always null?
Here is my code:
public class NewsListFragment extends ListFragment {
private final int topNewsCount = 5;
private DBNewsDataSource dataSource;
private Activity myActivity;
private Context myContext;
private boolean isHome;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isHome = true;
myActivity = getActivity();
Bundle extras = myActivity.getIntent().getExtras();
if (extras != null) {
isHome = extras.getBoolean("isHome");
}
dataSource = new DBNewsDataSource(getActivity());
dataSource.open();
List<DBNews> news = dataSource.getAllNews();
List<String> titleList = new ArrayList<String>();
dataSource.close();
for(int i = 0; i< (isHome?topNewsCount:news.size()); i++)
{
titleList.add(news.get(i).getTitle());
}
NewsListArrayAdapter adapter = new NewsListArrayAdapter(getActivity(),news,titleList,isHome);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something with the data
}
public void addHeader(View v)
{
ListView lv = getListView();
lv.addHeaderView(v);
}
Here is the activity that call the Fragment
public class HomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.template_activity_home);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
NewsListFragment frgNews = new NewsListFragment();
MainSlideShowFragment frgSS = new MainSlideShowFragment();
View vw = frgSS.getView();
frgNews.addHeader(vw);
fragmentTransaction.add(R.id.layout_news_list , (Fragment) frgNews);
fragmentTransaction.commit();
//frgNews.addHeader(vw);
}
Override onCreate view and let it returns a View wich contains a ListView with id android:id="#android:id/list"
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.cart_list,
null);
return view;
}
You are using a fragment but haven't called
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
This is where the layout will be inflated. Hence it is null as it is not yet inflated.

Categories

Resources