Control layout object in fragment - getting null object reference - java

I made a fragment_console.xml and ConsoleFragment.java
In MainActivity.java I create object console_fragment = new ConsoleFragment();
Then OnClickListener runs console_fragment.method();
But it gives error Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
on line
sendButton = v.findViewById(R.id.fragment_console_send_button);
ConsoleFragment.java
public class ConsoleFragment extends Fragment {
View v;
private boolean isVisible;
private Button sendButton;
private TextView consoleText;
private EditText commandText;
public ConsoleFragment() {
// Required empty public constructor
}
#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
v = inflater.inflate(R.layout.fragment_console, container, false);
showConsole(v);
return v;
}
public void showConsole(View v){
sendButton = (Button) v.findViewById(R.id.fragment_console_send_button);
consoleText = (TextView) v.findViewById(R.id.fragment_console_log_text);
commandText = (EditText) v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConsoleFragment console_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console_fragment = new ConsoleFragment();
}
public void triggerConsole(View view) { //buton on click
console_fragment.showConsole(view);
}
}
fragment_console.xml
<?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="wrap_content"
tools:context=".activities.ConsoleFragment">
<TextView
android:id="#+id/fragment_console_log_text"
android:layout_width="match_parent"
android:layout_height="150dp"
android:text="TextView"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent">
<EditText
android:id="#+id/fragment_console_command_text"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="0.75"
android:layout_marginBottom="2dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="#string/console_command"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/fragment_console_send_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="0.25"
android:text="#string/console_send_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
activity_main.xml
<?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"
tools:context=".activities.MainActivity">
<include
android:id="#+id/include"
layout="#layout/activity_top_bar"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragment"
android:name="com.wordfall.wordfallcontroll.activities.ConsoleFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/include2"
app:layout_constraintStart_toStartOf="parent" />
</FrameLayout>
<include
android:id="#+id/include2"
layout="#layout/activity_bottom_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
How to get layout object (buttons, tv etc) to get control on it in fragment class?

public class XFragment extends Fragment {
View v;
private boolean isVisible;
private Button sendButton;
private TextView consoleText;
private EditText commandText;
public XFragment() {
// Required empty public constructor
}
#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
v = inflater.inflate(R.layout.fragment_x, container, false);
showConsole(v);
return v;
}
public void showConsole(View v){
sendButton = v.findViewById(R.id.fragment_console_send_button);
consoleText = v.findViewById(R.id.fragment_console_log_text);
commandText = v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
}
In your activity_main.xml file you need to create a container for holding fragments like:
activity_main.xml
<LinearLayout
......
......
....
>
.........
........
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
In your MainActivity.java file inside onCreate method you can do:
MainActivity.java
#Override
protected void onCreate(...){
.....
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ConsoleFragment(), "ConsoleFragment").addToBackStack(null).commit();
}

What view you pass into triggerConsole method from outside fragment? The problem may be in this, you'll try to find controls in layout, which is not part of your fragment. View of your fragment is assigned to global variable v, but now you try to get it from method parameter named v. Try this code.
public void showConsole(){
sendButton = (Button) v.findViewById(R.id.fragment_console_send_button);
consoleText = (TextView) v.findViewById(R.id.fragment_console_log_text);
commandText = (EditText) v.findViewById(R.id.fragment_console_command_text);
isVisible = true;
sendButton.setVisibility(View.GONE);
consoleText.setVisibility(View.GONE);
commandText.setVisibility(View.GONE);
}
If you want pass different layouts into same fragment, do it via constructor, not via method parameter, and each time make new instance of fragment.

Related

Null pointer error when calling communicating between an activity and a fragement

I have been attempting to call a method from my home activity which should fire once a button is clicked on my settings fragment. The result of this button click should call the greenTorso() and swap an image on my avatar fragment. I am currently getting a null pointer error, please see the logcat attached. I'm not even sure if this is the right way to go about this, but been stuck for a couple of days now and hoped someone could help. Thanks in advance.
My home activity:
public class Home extends AppCompatActivity implements SettingsFragment.Communicator {
private TextView name, email;
Button LogoutButton;
UserSessionManager sessionManager;
Button button;
ImageView Torso;
public void communicateWith(){
AvatarFragment avatarFragment = (AvatarFragment)getSupportFragmentManager().findFragmentById(R.id.nav_avatar);
avatarFragment.greenTorso();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
getWindow().setBackgroundDrawableResource(R.drawable.background2); // sets background to background2.png
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // hides keyboard on boot
sessionManager = new UserSessionManager(getApplicationContext());
TextView lblName = (TextView) findViewById(R.id.lblName);
TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
if(sessionManager.checkLogin())
finish();
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
// get name
String name = user.get(UserSessionManager.KEY_NAME);
// get email
String email = user.get(UserSessionManager.KEY_EMAIL);
//lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
lblEmail.setText(Html.fromHtml("Welcome: <b>" + email + "</b>"));
LogoutButton=(Button)findViewById(R.id.LogoutButton);
Toast.makeText(getApplicationContext(),
"User Login Status: " + sessionManager.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
LogoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Clear the User session data
// and redirect user to LoginActivity
sessionManager.logoutUser();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_steps:
selectedFragment = new HomeFragment();
break;
case R.id.nav_avatar:
selectedFragment = new AvatarFragment();
break;
case R.id.nav_settings:
selectedFragment = new SettingsFragment();
break;
}
getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
My settings fragment:
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
private Communicator interfaceImplementor;
public interface Communicator
{
public void communicateWith();
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
this.interfaceImplementor = (Communicator)context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_settings, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ImageView torso = (ImageView) getActivity().findViewById(R.id.Torso);
interfaceImplementor.communicateWith();
}
});
}
}
My avatar fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
return rootView;
}
public void greenTorso()
{
ImageView IV =(ImageView) getActivity().findViewById(R.id.Torso);
IV.setBackgroundResource(R.drawable.torso2green);
}
}
Avatar layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:src="http://schemas.android.com/apk/res-auto"
android:background="#android:color/holo_orange_dark"
>
<ImageView
android:layout_width="500dp"
android:layout_height="530dp"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:id="#+id/Torso"
android:src="#drawable/torso2" >
</ImageView>
</RelativeLayout>
Settings layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:background="#D3D3D3"
android:weightSum="10"
tools:context=".Home">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="100dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shop"
android:textSize="26sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="10dp"/>
<androidx.cardview.widget.CardView
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/cardview"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:layout_marginRight="16dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="15dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="Green Torso"
android:textColor="#color/cardview_dark_background"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/ShopGreenTorso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/torso2green" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="bottom"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/register_button"
android:shadowColor="#color/colorPrimary"
android:text="10,000S Buy"
android:textColor="#color/white">
</Button>
</androidx.cardview.widget.CardView>
My navigation:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_steps"
android:icon="#drawable/ic_directions_walk_black_24dp"
android:title="Steps" />
<item
android:id="#+id/nav_avatar"
android:icon="#drawable/ic_face_black_24dp"
android:title="Avatar" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_build_black_24dp"
android:title="Settings" />
</menu>

How to fix TextView being rendered blank on new Activity

I'm trying to start another activity after clicking on a CardView inside a RecyclerView. The new activity renders after the click on any of the items inside the RecyclerView (It does the transition and changes the title TextView), but it does not show any of the TextView's inside the CardView on the layout.
The OnClick method is being set as an interface and being implemented in the first Activity.
Here is my first activity. I'm loading the data here from a SQLite database, but it's not relevant for the question to show the code from it.
public class MainActivity extends AppCompatActivity implements RecipeAdapterMain.OnCardListener {
private TextView tv;
ArrayList<RecipeObject> recipes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rv = findViewById(R.id.recipeListMain);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
RecipeAdapterMain adapter = new RecipeAdapterMain(recipes, this);
rv.setAdapter(adapter);
tv = findViewById(R.id.title);
}
#Override
public void onCardClick(int position) {
Intent intent = new Intent(this, RecipeActivity.class);
startActivity(intent);
}
}
This is my Adapter.
public class RecipeAdapterMain extends RecyclerView.Adapter<RecipeAdapterMain.RecipeListViewHolder> {
RecyclerView mRecyclerView;
ArrayList<RecipeObject> recipeList;
private OnCardListener mOnCardListener;
public RecipeAdapterMain(Context context, ArrayList<RecipeObject> recipeList, OnCardListener onCardListener) {
this.mOnCardListener = onCardListener;
this.recipeList = recipeList;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RecipeListViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_recipe_main, parent, false);
RecipeListViewHolder rcv = new RecipeListViewHolder(layoutView, mOnCardListener);
return rcv;
}
#Override
public void onBindViewHolder(#NonNull RecipeListViewHolder holder, int position) {
holder.mName.setText(recipeList.get(position).getName());
}
#Override
public int getItemCount(){
return recipeList.size();
}
public class RecipeListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mName;
OnCardListener onCardListener;
public RecipeListViewHolder(final View view, OnCardListener onCardListener) {
super(view);
mName = view.findViewById(R.id.textViewTitle);
this.onCardListener = onCardListener;
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onCardListener.onCardClick(getAdapterPosition());
}
}
public interface OnCardListener {
void onCardClick(int position);
}
}
My second activity:
public class RecipeActivity extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.layout_recipe);
}
}
This is the layout from the second activity. (layout_recipe):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test"
android:textColor="#1A1A1A"
android:textSize="18sp" />
<TextView
android:id="#+id/textViewIngr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test"
android:textColor="#1A1A1A"
android:textSize="18sp" />
<TextView
android:id="#+id/textViewDire"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test"
android:textColor="#1A1A1A"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And this is the layout from the first activity (activity_main):
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recipeListMain"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="#color/colorAccent"
android:layout_gravity="end|bottom"
android:layout_margin="16dp"
android:layout_marginBottom="16dp"
android:contentDescription="#string/submit"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:onClick="openActivityCreate"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
From clicking in a Card on the MainActivity, I expected to render the second activity with it's TextViews (This is a test), but it's rendering a blank page instead.
try removing #Nullable PersistableBundle persistentState from onCreate on your second activity

ViewPager and his fragments

Like a lot of other people on the stackoverflow, for example:
https://ru.stackoverflow.com/questions/571704/%D0%A0%D0%B0%D0%B7%D0%BD%D1%8B%D0%B9-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82-%D0%BD%D0%B0-%D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D0%B0%D1%85-viewpager
I'm trying to create ViewPager with different layouts, but with:
https://github.com/ogaclejapan/SmartTabLayout
Expectation: beautiful ViewPager with 3 tabs, which can switch different layouts/fragments by clicking on the buttons or by swipe.
Reality: beautiful ViewPager with 3 tabs, which are doing nothing.
Looking for your help, thanks.
What I have done in MainActivity class:
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setElevation(0); //toolbar shadow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ViewGroup tab = findViewById(R.id.linear_test);
tab.addView(LayoutInflater.from(this).inflate(R.layout.activity_main, tab, false));
ViewPager viewPager = findViewById(R.id.viewpager);
SmartTabLayout viewPagerTab = findViewById(R.id.viewpagertab);
setup(viewPagerTab);
FragmentPagerItems pages = new FragmentPagerItems(this);
pages.add(FragmentPagerItem.of("Вкладка 1", DemoFragment.class));
pages.add(FragmentPagerItem.of("Вкладка 2", DemoFragment.class));
pages.add(FragmentPagerItem.of("Вкладка 3", DemoFragment.class));
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), pages);
viewPager.setAdapter(adapter);
viewPagerTab.setViewPager(viewPager);
}
public void setup(final SmartTabLayout layout) {
//Do nothing.
}
}
What I have done in my DemoFragment:
public class DemoFragment extends Fragment {
static final String ARGUMENT_PAGE_NUMBER = "arg_page_number";
private int page;
static DemoFragment newInstance(int page) {
DemoFragment pageFragment = new DemoFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// View view = inflater.inflate(R.layout.activity_main, container, false);
page = getArguments().getInt("someInt", 0);
return inflater.inflate(R.layout.activity_main, container, false);
// return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
int position = FragmentPagerItem.getPosition(getArguments());
getItem(position);
}
public Fragment getItem(int position) {
switch (position) {
case 0: // Fragment # 0 - This will show FirstFragment
return DemoFragment.newInstance(1);
case 1: // Fragment # 0 - This will show FirstFragment different title
return DemoFragment.newInstance(2);
case 2: // Fragment # 1 - This will show SecondFragment
return DemoFragment.newInstance(3);
default:
return null;
}
}
}
Here is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<LinearLayout
android:id="#+id/linear_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"
android:background="#color/colorPrimary"
android:orientation="horizontal" >
<com.ogaclejapan.smarttablayout.SmartTabLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewpagertab"
android:layout_width="match_parent"
android:layout_height="#dimen/tab_height_large"
app:stl_customTabTextLayoutId="#layout/test_layout"
app:stl_customTabTextViewId="#id/custom_tab_text"
app:stl_distributeEvenly="true"
app:stl_defaultTabTextAllCaps="false"
app:stl_indicatorInterpolation="linear"
app:stl_defaultTabTextColor="#color/white"
app:stl_indicatorColor="#color/colorBlue"
app:stl_underlineColor="#color/colorBlue"
app:stl_defaultTabBackground="#color/colorPrimary"
app:stl_indicatorThickness="3dp"
app:stl_underlineThickness="1dp"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/viewpagertab"
/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/playlist_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linear_test" />
<TextView
android:id="#+id/dl_params"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:visibility="gone"
android:layout_weight="1"
tools:ignore="MissingConstraints"/>
</android.support.constraint.ConstraintLayout>
And finally test_layout which one is filling those SmartTabLayout:
<?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"
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
>
<android.support.v4.widget.Space
android:id="#+id/center_anchor"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerInParent="true"
/>
<aectann.pr1.TintableImageView
android:id="#+id/custom_tab_icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_above="#id/center_anchor"
android:layout_centerHorizontal="true"
android:scaleType="center"
android:src="#drawable/custom_icon"
/>
<TextView
android:id="#+id/custom_tab_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/center_anchor"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:maxLines="1"
android:textSize="14sp"
android:textColor="#color/white"
/>
</RelativeLayout>
Any ideas, guys?

Efficient way to display data

I am creating an app that has a fragment where a user can open a spinner using a button and select a food item. The food item will then be displayed under the button in a list. I have tried creating textviews and making invisible textviews and setting the text later, but none have worked. I was wondering if anyone knew of a better way of creating this that I'm not seeing.
<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"
tools:context="com.lastineindustries.ingredismartv2.Kitchen">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:text="Add An Ingredient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/add"
android:textSize="30sp"
android:layout_gravity="center" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="320dp"
android:layout_height="match_parent"
android:id="#+id/main"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/valueButton"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
</LinearLayout>
Is this what you want?
Then, read my code.
code of ChooseFoodFragment.java and its layout file:
public class ChooseFoodFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_choose_food, container, false);
initViews(v);
return v;
}
private Button btn_add;
private ListView listView;
private List<String> mData = new ArrayList<>();
private ArrayAdapter<String> mAdapter;
private void initViews(View v) {
listView = v.findViewById(R.id.list);
mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, mData);
listView.setAdapter(mAdapter);
btn_add = v.findViewById(R.id.add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChooseFoodDialog dialog = new ChooseFoodDialog();
dialog.setOnSelectedListener(new ChooseFoodDialog.OnSelectedListener() {
#Override
public void onSelected(String name) {
mData.add(name);
mAdapter.notifyDataSetChanged();// update the list of selected food
}
});
dialog.show(getFragmentManager(), "");//show the spinner items to select
}
});
}
}
fragment_choose_food.xml,just remove other views except the root view and the button, then add a ListView.
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lastineindustries.ingredismartv2.Kitchen">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Add An Ingredient"
android:textSize="30sp" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp" />
</LinearLayout>
</FrameLayout>
the code of ChooseFoodDialog.java and its layout file.
public class ChooseFoodDialog extends DialogFragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = LayoutInflater.from(getContext()).inflate(R.layout.dialog_choose_food, container, false);
initViews(v);
return v;
}
private ListView lv;
private List<String> mData = new ArrayList<>();
private void initViews(View v) {
// prepare some temp data
for (int i = 0; i < 10; i++) {
mData.add("Ingredients_" + i);
}
lv = v.findViewById(R.id.lv_ingredients);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String ingredient = mData.get(i);
if (mListener != null) {
mListener.onSelected(ingredient);// when the item of food is selected
}
dismiss();
}
});
}
private OnSelectedListener mListener;
public void setOnSelectedListener(OnSelectedListener listener) {
mListener = listener;
}
interface OnSelectedListener {
void onSelected(String name);
}
}
dialog_choose_food.xml,that's simple.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lv_ingredients"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
run the program, check it.
You should use ListView or RecyclerView for such tasks. Check out example from official Android documentation: link.

ViewPager and Fragments: Why do I always see the same thing?

I have created a ViewPager with three "pages". The code is this
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);
FragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
getSupportFragmentManager());
viewPager.setAdapter(fragmentPagerAdapter);
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColor(Color.DKGRAY);
}
}
MyFragmentPageAdapter.java
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private String[] pageTitle = {
"Page1", "Page2", "Page3"
};
public MyFragmentPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putString("pageIndex", Integer.toString(position + 1));
fragment.setArguments(arguments);
return fragment;
}
#Override
public int getCount() {
return pageTitle.length;
}
#Override
public CharSequence getPageTitle(int position) {
return pageTitle[position];
}
}
PageFragment.java
public class PageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
return view;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33B5E5"
android:textColor="#FFFFFF"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_page.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:textSize="16sp"
android:textStyle="italic"
android:gravity="center_horizontal"
android:textColor="#color/red"
android:text="#string/inf" />
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="60dp"
android:textSize="28sp"
android:gravity="center_horizontal"
android:textStyle="bold"
android:text="#string/ben" />
<TextView
android:id="#+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="130dp"
android:gravity="center_horizontal"
android:textSize="18sp"
android:text="Prova"
/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_centerInParent="true"
android:text="#string/verifica" />
</RelativeLayout>
But now i visualize in all three pages the same thing. If I for example on page 2 I want a TextView with the text "This is the 2 page" and on the third page a TextView with the text "This is the page 3" and in the first page two TextView with the button ... how can I? I'm going crazy, please let pass me the code to do this thing. Please.
Once you inflate PageFragment's layout you need to get a reference of the TextView so you can display the position on it via the Bundle you are passing using setArguments(). Use your view variable inside onCreateView() to get a reference of the TextView. (i.e. view.findViewById()). Then use getArguments() in your PageFragment to retrieve the Bundle with that has position, and set the TextView to that value.
this is a good example for what you want.
Just create a function in your page fragment class to configure elements and modify onCreateView to attach childs.
public class PageFragment extends Fragment {
TextView tv1 ;
// ...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
/// Attach your childs
tv1 = view.findViewById(R.id.textView1);
return view;
}
public void configure(int position) {
tv1 .setText("This is "+ position);
}
}
Then just call the function configure in getItem function
#Override
public Fragment getItem(int position) {
PageFragment fr = new PageFragment();
fr.configure(position + 1);
return fr;
}

Categories

Resources