1

I am working on my app and I just implemented a bottom navigation that scrolls through fragments when the respected tab is selected. I added a recyclerview also into my home fragment. Everything works properly except for one issue. When I open the app, the app will load into the Home Fragment, which I want, but the alerts icon is selected and the text box is selected, which I don't want. When I click on any of the icons, the fragments work the way they should. I just want the app to open, and load the app on the home fragment with the home icon selected and the searchbox isn't selected. I have attached images at the bottom to show what I mean. I have been looking and trying everything but know luck. How can I solve this?

I didn't post my entire alerts/favorite fragment code but the XML is just a simple text box and the java code is just the standard below for both:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_"alert or favs", container, false);

Main Activity

public class MainActivity extends AppCompatActivity implements 
BottomNavigationView.OnNavigationItemSelectedListener{

private FirebaseAuth firebaseAuth;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    firebaseAuth = FirebaseAuth.getInstance();

    loadFragment(new HomeFragment());
    BottomNavigationView navigation= findViewById(R.id.bottom_navigation);
    navigation.setOnNavigationItemSelectedListener(this);

}

private void user_logout() {
    firebaseAuth.signOut();
    finish();
    startActivity(new Intent(MainActivity.this, SignIn.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.logoutMenu: {
            user_logout();
        }
    }
    return super.onOptionsItemSelected(item);
}

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment selectedFragment = null;

        switch (item.getItemId()) {

            case R.id.ic_home:
                selectedFragment = new HomeFragment();
                break;
            case R.id.ic_alert:
                selectedFragment = new AlertFragment();
                break;
            case R.id.ic_favorite:
                selectedFragment = new FavoriteFragment();
                break;
            default:
                selectedFragment = new HomeFragment();
                break;
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();

        return loadFragment(selectedFragment);
    }


private  boolean loadFragment(Fragment fragment){
    if( fragment != null){
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
        return true;
    } return false;
 }
}

Main Activity XML

<?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:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container">
   <FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/bottom_navigation">
    </FrameLayout>
    <android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:menu="@menu/bottom_nav_menu"
    android:background="?android:attr/windowBackground"/>
   </RelativeLayout>

Home Fragment

public class HomeFragment extends Fragment {

private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
private RecyclerView recyclerView;
private EditText SearchText;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup 
container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_home, container, false);

    listItems = new ArrayList<>();
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
    SearchText = (EditText) v.findViewById(R.id.search_text);

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    loadRecyclerViewData();

    SearchText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            filter(editable.toString());
        }
    });

    return v;
}


private void filter(String text){
    List<ListItem> filteredList = new ArrayList<>();

    for(ListItem item :listItems ){
        if (item.getHead().toLowerCase().contains(text.toLowerCase()) || item.getDesc().toLowerCase().contains(text.toLowerCase())){
            filteredList.add(item);
        }
    }
    adapter = new MyAdapter(filteredList, getContext());
    recyclerView.setAdapter(adapter);
}



private void loadRecyclerViewData() {
    final ProgressDialog progressDialog = new ProgressDialog(getContext());
    progressDialog.setMessage("Loading Data...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET,
            URL_DATA,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    progressDialog.dismiss();
                    try {
                        JSONArray array = new JSONArray(response);


                        for(int i=0; i < array.length(); i++){
                            JSONObject o = array.getJSONObject(i);
                            ListItem item = new ListItem(
                                    o.getString("name"),
                                    o.getString("symbol"),
                            );

                            listItems.add(item);
                        }
                        adapter = new MyAdapter(listItems, getContext());
                        recyclerView.setAdapter(adapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressDialog.dismiss();
                    Toast.makeText(getContext(),error.getMessage(), Toast.LENGTH_LONG).show();

                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(stringRequest);
}

Home Fragment XML

 <?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:app="http://schemas.android.com/apk/res-auto"
android:background="#28394D">

<EditText
    android:id="@+id/search_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@drawable/ic_search_black_24dp"
    android:hint="Enter Coin Name"
    android:textSize="25dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dp"
    android:background="@drawable/rounded_edittext"
    android:layout_marginBottom="5dp" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/search_text"
    android:background="#28394D">

</android.support.v7.widget.RecyclerView>

</RelativeLayout>

My Adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;

public MyAdapter(List<ListItem> listItems, Context context) {
    this.listItems = listItems;
    this.context = context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_item, parent, false);

    return new ViewHolder(v);

}


@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    final ListItem listItem = listItems.get(position);

    holder.textViewHead.setText(listItem.getHead());

}

@Override
public int getItemCount() {
    return 50;
}

public void filterList(ArrayList<ListItem> filteredList){
    this.listItems = filteredList;
    notifyDataSetChanged();
}

How it looks now

How it should look

nyjxrb30
  • 78
  • 1
  • 3
  • 11

2 Answers2

1

1. Default to Home fragment

I noticed that you've already accepted an answer in your duplicate question.

2. EditText without focus

Add android:focusableInTouchMode="true" to the element <RelativeLayout> in Home fragment XML, as below. It changes the focus from EditText to its parent, and soft keyboard won't appear.

<?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"
    android:background="#28394D"
    android:focusableInTouchMode="true">

    <EditText
        android:id="@+id/search_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_search_black_24dp"
        android:hint="Enter Coin Name"
        android:textSize="25dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/rounded_edittext"
        android:layout_marginBottom="5dp" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/search_text"
        android:background="#28394D"/>

</RelativeLayout>

I've found the following questions about it.

qtmfld
  • 2,916
  • 2
  • 21
  • 36
0

To remove softkeyboard appearing when u load fragment with EditText, use this solution which I tried and worked

FragmentClass:

public class Fragment1 extends Fragment {
EditText editText;
LinearLayout lyt;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_getcode, container, false);
     editText = (EditText)view.findViewById(R.id.search_bar);
     lyt = (LinearLayout) view.findViewById(R.id.getcode_mainlyt);

    if (lyt instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) lyt).getChildCount(); i++) {
            View innerView = ((ViewGroup) lyt).getChildAt(i);
            setupUI(innerView);
        }
    }
    editText.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View view, MotionEvent motionEvent) {
            // your code here....
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
           // editTextHintView.setVisibility(View.GONE);
            return false;
        }
    });

    return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public static void hideSoftKeyboardForFragment(Activity activity) {
    try {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    } catch (Exception e) {

    }
}


public void setupUI(View view) {
    // Set up touch listener for non-text box views to hide keyboard.
    if (!(view instanceof EditText)) {
        view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboardForFragment(getActivity());
                if (editText.getText().toString().trim().isEmpty()) {
                    // editTextHintView.setVisibility(View.VISIBLE);
                }
                return false;
            }
        });
    }
}

}

Fragment xml:

 <LinearLayout
android:id="@+id/getcode_mainlyt"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
    android:id="@+id/search_bar"
    android:layout_width="match_parent"
    android:layout_height="51dp"
    android:clickable="true"
    android:focusableInTouchMode="true"
    android:inputType="text"
    android:layout_marginTop="7dp"
    android:layout_marginLeft="7dp"
    android:layout_marginRight="7dp"
    android:layout_marginBottom="7dp"
    android:background="@android:color/darker_gray" />

dev
  • 260
  • 2
  • 12