I have android project that have three tabs. in one of 3 tabs has a ListView of different activities in which if that item clicked should come direct to assigned fragment
those tabs are TABA TABB TABC on TABB that has list of activities in which if someone click should direct to another fragment and activities containing these tabs should not be shown
I tried to call those fragmenttransaction inside istView.setOnItemClickListener but no any thing change
In tabs TABB
here are the code
public class Activities extends Fragment implements View.OnClickListener{
private SectionsPagerAdapter sectionsPagerAdapter;
public Activities() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activities, container, false);
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for(int i = 0; i<7; i++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("listview_title", ListTitle[i]);
hm.put("listview_image", Integer.toString(ListImage[i]));
aList.add(hm);
}
String [] from = {"listview_image", "listview_title"};
int [] to = {R.id.listview_image, R.id.listview_item_title};
SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(),aList,
R.layout.activity_listview, from, to);
ListView listView = (ListView)rootView.findViewById(R.id.list_view);
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//R.id.container is on activity_main.xml
transaction.replace(R.id.container, new FileDownloadFragment());
transaction.commit();
}
});
return rootView;
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<!--!app:layout_scrollFlags="scroll|enterAlways"-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed">
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<!-- <android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />-->
</LinearLayout>
fragment_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.jeliel.easycontrol.activities.Activities">
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I'm expecting this when item clicked on ListView should bring me on fragment called FileDownloadFragment()
Related
I have an application that contains TabLayout with 5 tabs.
Now the need arose to click on an item in the RecycleView to open a new fragment within the Fragment that the user was already using, as if clicking on the item opened the subitems
My problem is that it uses ViewPager(Container)
In the parent Fragment I have the following code
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position){
// MyListModel model = mList.get(holder.getAdapterPosition());
switch(holder.getItemViewType()){
case 1:{
MyViewHolder viewHolder = (MyViewHolder) holder;
viewHolder.Name.setTextColor(Color.parseColor("#245251")); //Todo Muda a cor da linha dos itens do RecycleView 08-08-2022
String nome = telemensagens.get(position).getName();
//String pasta = nome.substring(0,nome.lastIndexOf('-') );
String pasta = nome.lastIndexOf('_')>0 ? nome.substring(0,nome.lastIndexOf('_') ) : nome;
String index = nome.substring(nome.lastIndexOf('_') + 1).trim();
viewHolder.Name.setText(pasta);//telemensagens.get(position).getName());
viewHolder.Email.setText(telemensagens.get(position).getUrl());
final String music = telemensagens.get(position).getUrl();
viewHolder.Name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment myFragment;
/* Intent intent = new Intent(context, TelemensagensItensActivity.class);
intent.putExtra("PASTA", telemensagens.get(position).getName() );
context.startActivity(intent);*/
Bundle bundle = new Bundle();
String nome = telemensagens.get(position).getName();
if(MainActivity.nivelPasta==0)
MainActivity.nivelPastaFinal = nome.lastIndexOf('_')>0 ? Integer.parseInt(nome.substring(nome.lastIndexOf('_') + 1).trim()) : 1;
//MainActivity.nivelPastaFinal = Integer.parseInt(telemensagens.get(position).getName().substring(telemensagens.get(position).getName().length()-1,telemensagens.get(position).getName().length()));
MainActivity.nivelPasta++;
if(MainActivity.nivelPasta==MainActivity.nivelPastaFinal) {
myFragment = new AudiosItensActivity();
bundle.putString("PASTA",telemensagens.get(position).getName() );
MainActivity.audios.add(telemensagens.get(position).getName());
}
else {
myFragment = new AudiosActivity();
MainActivity.audios.add(telemensagens.get(position).getName());
bundle.putString("PASTA", MainActivity.nomePasta+ telemensagens.get(position).getName() );
MainActivity.nomeAudio += telemensagens.get(position).getName() + "/";
}
AppCompatActivity activity = (AppCompatActivity) context;
myFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, myFragment,"Audio").
addToBackStack(null).commit();
}
});
break;
}
case 2:{
break;
}
}
}
In this specific piece of code is the click of the item in the recycleView, when clicking on it I can open a new child fragment, BUT it ends up killing my TabLayout, that is, the tabs stop working and I can no longer navigate in the other tabs
AppCompatActivity activity = (AppCompatActivity) context;
myFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, myFragment,"Audio").addToBackStack(null).commit();
So my question is: How can I replace a single fragment and not my entire container with all fragments
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:fitsSystemWindows="true">
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.testapp.EventActivity">
<RelativeLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/coordinator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/adViewMob"
android:layout_weight="1">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"
app:tabTextAppearance="#style/MinhaCustomTabText" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/adViewMob"
android:layout_marginBottom="2dp"
android:animateLayoutChanges="true"
android:fitsSystemWindows="false"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adViewMob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom"
android:layout_marginTop="5dp"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/ad_unit_id" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="170dp">
<com.dvinfosys.ui.NavigationListView
android:id="#+id/expandable_navigation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left"
android:divider="#null"
android:groupIndicator="#null"
android:scrollbars="vertical" />
</ScrollView>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
fragment_container.xml
<FrameLayout
xmlns:ads="http://schemas.android.com/apk/res-auto"
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:layout_above="#id/adViewMob"
tools:context="com.mobileboss.bomdiatardenoite.ContainerFragment"
>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/adViewMob"
android:layout_marginBottom="0dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?actionBarSize"
android:id="#+id/rltLayout"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
</RelativeLayout>
</FrameLayout>
its image showing value and search bar
it is the image showing when clicking the search bar it will come up the values in list-view
I want to know why this happen and how to avoid the situation please help me thanks in advance
public class ListItem extends AppCompatActivity
{
ListView listView1;
ArrayList<String> listproduct;
ArrayAdapter<String > adapternew;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listitem);
ActionBar actionBar=getSupportActionBar();
actionBar.setTitle("Please Select the Item");
SearchView search=(SearchView)findViewById(R.id.Search);
ScrollView scroll=(ScrollView)findViewById(R.id.Scroll);
ListView listView1=(ListView)findViewById(R.id.Listview);
listproduct=new ArrayList<>();
listproduct.add("Stove Top Stuffing");
listproduct.add("Campell's Soup");
listproduct.add("Tide");
listproduct.add("Pampers");
listproduct.add("Pepsi Products");
listproduct.add("Tang");
listproduct.add("Top Ramen");
listproduct.add("Knorr");
listproduct.add("Palmolive");
listproduct.add("Scotch-Brite");
listproduct.add("Bounty Paper Towls");
listproduct.add("Oreo Cookies");
listproduct.add("Quaker Oats");
listproduct.add("Lays Potato Chips");
adapternew = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listproduct);
listView1.setAdapter(adapternew);
SearchManager manager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
search.clearFocus();
if(listproduct.contains(query))
{
adapternew.getFilter().filter(query);
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapternew.getFilter().filter(newText);
return false;
}
});
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int newposition, long id) {
Toast.makeText(ListItem.this,listproduct.get(newposition)+"",Toast.LENGTH_SHORT).show();
Intent i=new Intent(ListItem.this,AddOrder.class);
i.putExtra("position",listproduct.get(newposition));
//adapternew.notifyDataSetChanged();
startActivity(i);
}
});
}
}
here is the code that is to show the list view item and i want to know whether the value in list view come up when clicking the search bar
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<SearchView
android:id="#+id/Search"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentTop="true"
android:iconifiedByDefault="false"
android:queryHint="Search Here"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.00" />
<ScrollView
android:id="#+id/Scroll"
android:layout_width="100dp"
android:layout_height="150dp"
tools:layout_editor_absoluteX="-8dp"
tools:layout_editor_absoluteY="396dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
tools:layout_editor_absoluteX="9dp"
tools:layout_editor_absoluteY="2dp" />
<ListView
android:id="#+id/Listview"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#id/Search"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.100"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.200">
</ListView>
</androidx.constraintlayout.widget.ConstraintLayout>
and this is the xml file of the listview
I think this is the code you are wanting.
No need to use scrollview here because ListView itself is scrollable. LinearLayout with Vertical Orientation will solve your issue
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
tools:layout_editor_absoluteX="9dp"
tools:layout_editor_absoluteY="2dp" />
<SearchView
android:id="#+id/Search"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentTop="true"
android:iconifiedByDefault="false"
android:queryHint="Search Here"/>
<ListView
android:id="#+id/Listview"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_marginTop="10dp">
</ListView>
</LinearLayout>
I think with ConstraintLayout , you can use app:layout_constraintTop_toBottomOf to assign it below the desired view instead of layout_below
<ListView
android:id="#+id/Listview"
android:layout_width="match_parent"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.100"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/search" <!-- change here -->
app:layout_constraintVertical_bias="0.200">
I'm trying to set a TextView that's in a fragment but the text won't update in the view. The text is 1 of 2 pages in a ViewPager. The ViewPager is inside another fragment that has a button which when clicked uses an interface to the MainActivity that calls the changeText() that's inside the fragment with my text.
Fragment Inside ViewPager:
public class PlaceholderFragment extends Fragment {
public TextView textFV;
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_pull, container, false);
textFV = rootView.findViewById(R.id.textFV);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void changeText() {
textFV.setText("Test"); - Won't update view.
System.out.println(textFV.getText()); - Shows correct text.
}
}
Relevant part of Fragment that contains ViewPager:
OnHeadlineSelectedListener callback;
public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener callback) {
this.callback = callback;
}
public interface OnHeadlineSelectedListener {
void onArticleSelected();
}
//...
#Override
public void onClick (View v) {
callback.onArticleSelected();
}
Relevant MainActivity Part:
public void onArticleSelected() {
PlaceholderFragment articleFrag = (PlaceholderFragment) getSupportFragmentManager().findFragmentById(R.id.viewpager);
if (articleFrag != null) {
articleFrag.changeText();
}
}
Here is the layout that contains the TextView:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior">
<LinearLayout
android:id="#+id/tab_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:id="#+id/containerPull"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="#+id/textsLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/label_left_margin"
android:layout_marginTop="5dp"
android:text="#string/label_common"
android:textColor="#color/colorLabelText"
android:textSize="18sp" />
<TextView
android:id="#+id/textFV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textColor="#android:color/black"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.constraint.ConstraintLayout>
Here's where the button and ViewPager is. The button is the ImageButton:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white">
<android.support.v7.widget.Toolbar
android:id="#+id/pullToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="Information"
app:titleTextAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title.Montserrat">
<ImageButton
android:id="#+id/toolbarButtonPull"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="1dp"
android:background="#drawable/button_toolbar_default"
android:contentDescription="Pull"
android:padding="15dp"
android:src="#drawable/ic_arrow_downward_black_24dp" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabTextAppearance="#style/TextAppearance.Design.Tab.NoCaps">
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab1" />
<android.support.design.widget.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab2" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior" />
</android.support.design.widget.CoordinatorLayout>
Looks like your textFV is inside layout that has visibility gone. Can it be the problem?
<LinearLayout
android:id="#+id/containerPull"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
**android:visibility="gone">**
<TextView
android:id="#+id/textsLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/label_left_margin"
android:layout_marginTop="5dp"
android:text="#string/label_common"
android:textColor="#color/colorLabelText"
android:textSize="18sp" />
<TextView
android:id="#+id/textFV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textColor="#android:color/black"
android:textSize="18sp" />
I need to set a ListView's Adapter which is located in a Fragment from an Activity.
I have tried to set the Adapter from the Activity with the code below, but it returns a NullPointerException, presumably because the Fragment has not been loaded yet.
ListView gradeListView = (ListView) this.findViewById(R.id.gradeListView);
gradeListView.setAdapter(new SimpleAdapter(this, item_list, list_layout, list_input, layout_values));
Is there a way to run the above code after the Fragment has loaded in, or a better way of doing this altogether? I have attempted to use a method that would set the Adapter inside the Fragment itself, but I still need to wait for the fragment to be loaded before I instigate it from the Activity or I will still receive a NullPointerException. I would also need to put an ArrayList<HashMap<String, String>> into a bundle, which there is no documentation on how to do so if I was going to use that method.
I have also tried to instigate a method that holds the set adapter code that is located inside the Activity from the Fragment's onActivityCreated() method which still returned a NullPointerException.
Am I not referencing the ListView element correctly from the Activity or is there a way to wait for the Fragment to load in, so I don't receive an error?
TabbedActivity.java / Main Parent Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(6);
mViewPager.setAdapter(mSectionsPagerAdapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
// ...
interpretGrades(retrieveGrades());
}
public void interpretGrades(String input) {
// take CLASSES~~MAINCLASSDIVIDER~~GRADES
// turn it into Classes = Classes
// Grades = Grades
final String[] ServerResponse = input.split("~~MAINCLASSDIVIDER~~");
final String[] Classes = ServerResponse[0].split(";");
final String[] Grades = ServerResponse[1].split(";");
ArrayList<HashMap<String, String>> item_list = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < Classes.length; i++) {
HashMap<String, String> item = new HashMap<String, String>();
String[] ClassSplit = Classes[i].split("-");
String Period = ClassSplit[0];
String Class = ClassSplit[1];
item.put("Period", Period);
// --.substring(1, --.length()) removes first character from string (in this case, a whitespace from the class name)
item.put("Class", Class.substring(1, Class.length()));
item.put("Grade", Grades[i]);
item_list.add(item);
}
String[] list_input = new String[] { "Period", "Class", "Grade" };
// PUT THE STRING VALUES FROM list_input INTO THE XML LAYOUT VALUES
int[] layout_values = new int[] { android.R.id.text1, android.R.id.text2, R.id.grade};
// LISTVIEW LAYOUT (XML FILE)
int list_layout = grade_list;
ListView gradeListView = (ListView) this.findViewById(R.id.gradeListView);
gradeListView.setAdapter(new SimpleAdapter(this, item_list, list_layout, list_input, layout_values));
}
Tab2Pulse.java / Fragment
public class Tab2Pulse extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.tab2chat, container, false);
return mainView;
}
}
tab2chat.xml / Fragment Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tab2chat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<TextView
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/gradeListView"
style="#android:style/Widget.Material.Light.ListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
activity_tabbed.xml / Main Activity Layout
<android.support.design.widget.CoordinatorLayout
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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="software.endeavor.projectg.TabbedActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/main_gradient"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<View
android:layout_width="match_parent"
android:layout_height="12dp" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#drawable/main_gradient"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#android:color/white" />
</android.support.design.widget.AppBarLayout>
<View
android:id="#+id/toolbar_shadow"
android:layout_width="match_parent"
android:layout_height="12dp"
android:layout_below="#id/toolbar"
android:background="#drawable/toolbar_dropshadow" />
<!--<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="368dp"
android:layout_height="495dp">-->
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
<!--</android.support.v4.widget.SwipeRefreshLayout>-->
</LinearLayout>
<View
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="#*android:dimen/navigation_bar_height"
android:background="#drawable/login_gradient" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
I have implemented a TabLayout which has a few tabs & one of the tabs has a table & when a user clicks on a row in the table I need it to get rid of the tab layout, except for the toolbar & open up a new Fragment.
I've tried a few different ways but nothing seems to work, if anyone has any ideas, it'll will be much appreciated!
Thank you!
Cheers!
This is the activity_main.xml
<RelativeLayout
android:id="#+id/main_layout"
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"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
& this is the MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
& this is tab1.xml
<FrameLayout 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="#F0F0F0" >
<ScrollView
android:id="#+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center" >
<TableLayout
android:id="#+id/table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
</TableLayout>
<RelativeLayout
android:id="#+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
</FrameLayout>
& this is Tab1.java
public class TopStories extends Fragment {
A lot of code goes here............
public void createTable() {
TableLayout table = (TableLayout) getActivity().findViewById(R.id.table);
table.setBackgroundColor(Color.rgb(240, 240, 240));
table.setStretchAllColumns(true);
table.setShrinkAllColumns(true);
table.removeAllViews();
TableRow row = new TableRow(getActivity());
row .setGravity(Gravity.CENTER);
row .setPadding(0, 10, 0, 10);
row .setBackgroundColor(Color.WHITE);
row .setClickable(true);
TableRow.LayoutParams params = new TableRow.LayoutParams();
row .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
This is where I need to start up the new fragment (NewFragment.Java).
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_topstories, container, false);
}
}
NewFragment.java
public class NewFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.newfragment, container, false);
}
}
newfragment.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" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="18dp"/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="87dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
I think you need to give the fragment somewhere to replace. Here is the XML from my app, and when I swap fragments, they post to flcontent.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk
xmlns:app="http://schemas.android.com/apk/res
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!-- The main content view -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
</LinearLayout>
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header"/>
and the class code
// Insert the fragment by replacing any existing fragment
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.flContent, fragment);
ft.addToBackStack(null);
ft.commit();
Alright so I think that I figured out a really cheap & a cheeky way to do this & probably not very healthy for the app but it works perfect!
Thank you very much for the help Brian! Appreciate it! Maybe you can do this for the backstack problem of your app as well, don't know if it will work or the right thing that you need to do though.
Cheers!
Added a FrameLayout to my main_activity.xml
<RelativeLayout
android:id="#+id/main_layout"
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"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</RelativeLayout>
Changed my newfragment.xml to this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fullStoryLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/fullStoryRelativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="80dp"/>
<TextView
android:id="#+id/fullStorytitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/fullStory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/image"
android:layout_marginTop="50dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</LinearLayout>
& added this to the onClick event of the table row
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().findViewById(R.id.tab_layout).setVisibility(View.GONE);
getActivity().findViewById(R.id.pager).setVisibility(View.GONE);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("New Fragment");
Fragment fragment = null;
Class fragmentClass = NewFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.flContent, fragment);
fragmentTransaction.commit();
}
});
& to go back to the main TabLayout from the NewFragment, I added this at MainActivity.java
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch(keyCode){
case KeyEvent.KEYCODE_BACK:
if (getSupportActionBar().getTitle() != "Main Activity"){
onBackPressed();
}
else {
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed(){
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle("Main Activity");
findViewById(R.id.fullStoryLinearLayout).setVisibility(View.GONE);
findViewById(R.id.tab_layout).setVisibility(View.VISIBLE);
findViewById(R.id.pager).setVisibility(View.VISIBLE);
}