У меня есть три фрагмента, которые я пытаюсь отобразить, щелкнув соответствующую опцию на панели навигации. У меня есть навигационный ящик, отображающий и открывающий / закрывающий нормально. Но я не могу получить какие-либо фрагменты для отображения в деятельности. Главный экран просто остается пустым, когда я нажимаю на опцию. Там нет ошибок компиляции. Я новичок в разработке для Android, а также в Java-разработчике, и я пытался завершить этот проект в течение месяца, поэтому он будет завершен, как только я смогу заставить это работать. Вы можете увидеть несколько экземпляров избыточного кода, потому что я просто хотел попробовать что-нибудь, что могло бы работать, и я не уверен, что удалять, поэтому любые пояснения по этому поводу тоже помогут.
Фрагменты должны отображаться как результаты в RecyclerView.
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nView;
private ActionBarDrawerToggle toggle;
private RequestQueue queue;
private List<ATM> atmList;
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find drawer layout
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find drawer view
nView = (NavigationView) findViewById(R.id.nav_view);
// Set up drawer view
setupDrawerContent(nView);
// Not sure what this does
nView.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(
this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// Tie DrawerLayout events to the ActionBarDrawerToggle
mDrawer.addDrawerListener(toggle);
queue = Volley.newRequestQueue(this);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
toggle.onConfigurationChanged(newConfig);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
/*
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (toggle.onOptionsItemSelected(item)) {
return true;
}
/* int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}*/
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_items_catalog) {
// Handle the items catalog action
} else if (id == R.id.nav_items_search) {
} else if (id == R.id.nav_atms) {
/*
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
// atmView = findViewById(R.id.atmRecyclerView);
// atmView.setHasFixedSize(true);
// atmView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(MainActivity.this, atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
*/
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_items_catalog:
fragmentClass = ShowItems.class;
// TODO: Find out how to show the fragments in these calls
// fragment.listItems(???);
break;
case R.id.nav_items_search:
fragmentClass = SearchItems.class;
break;
case R.id.nav_atms:
fragmentClass = ShowATMs.class;
/*
atmView = findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(this));
*/
break;
default:
fragmentClass = ShowItems.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
Метод ShowATMs - Хотите показать список объектов ATM в формате RecyclerView:
public class ShowATMs extends Fragment {
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
private RequestQueue queue;
// TODO: NEED TO CREATE A VIEW THAT WILL INFLATE CORRECT LAYOUT HERE
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Is this line needed?
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.atm_view, container, false);
atmView = rootView.findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(getContext()));
final List<ATM> atmList = new ArrayList<>();
queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(getContext(), atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
return rootView;
}
}
XML-файлы
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment android:name="com.camelr.bilal.camelrecommerceproject.Fragments.ShowATMs"
android:id="@+id/ATMs"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout="@layout/atm_view" />
<!-- The ActionBar displayed at the top -->
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="@+id/flContent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!--<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="@color/colorPrimary"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
atm_view.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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<!--
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">
-->
<android.support.v7.widget.RecyclerView
android:id="@+id/atmRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
У меня есть два других фрагмента, которые я настроил немного по-другому, но просто показываю один для банкоматов, потому что я чувствую, что он ближе всего к работе.