Для моего академического проекта я хочу создать приложение с 4 вкладками.Первая покажет последние игры, добавленные в список, вторая будет формой поиска, третья покажет результаты поиска, а последняя покажет детали.В настоящее время я создал код для TabView
и 4 вкладки.Проблема в том, что я хочу выполнить поиск, чтобы получить элементы, которые у меня есть в списке, которые соответствуют критериям поиска для фрагмента 2, но я не знаю, как передать данные из фрагмента 2 (данные textView и счетчик) во фрагмент3. Мой код следующий:
MainActivity.java
:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@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.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
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_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(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) {
}
});
}
}
TabPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
return new SearchResultsFragment();
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
@Override
public int getCount() {
return tabCount;
}
}
SearchFormFragment.java
package gr.pliroforiki_edu.videogamedb;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {@link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
Я хочу заархивировать следующие фрагменты:
ListActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ListActivity extends AppCompatActivity {
private TextView textViewInfo;
private ListView listViewBooks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Animation when this Activity appears
overridePendingTransition(R.anim.pull_in_from_right, R.anim.hold);
// Get user filters from Intent
Intent intent = getIntent();
String filterAuthor = intent.getStringExtra("AUTHOR");
String filterTitle = intent.getStringExtra("TITLE");
int filterGenreId = intent.getIntExtra("GENREID", 0);
findViews();
// Show user filters for information
String message = String.format("Author: %s\nTitle: %s\nGenreId: %d",
filterAuthor, filterTitle, filterGenreId);
textViewInfo.setText(message);
DataStore.LoadBooks(filterAuthor, filterTitle, filterGenreId);
//Complex Object Binding
ListAdapter booksAdapter = new SimpleAdapter(
this,
DataStore.Books,
R.layout.list_item,
new String[]{DataStore.KEY_TITLE, DataStore.KEY_AUTHOR, DataStore.KEY_GENRENAME},
new int[]{R.id.book_item_title, R.id.book_item_author, R.id.book_item_genre}
);
listViewBooks.setAdapter(booksAdapter);
listViewBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detailsIntent = new Intent(ListActivity.this, DetailsActivity.class);
detailsIntent.putExtra(DataStore.KEY_POSITION, position);
startActivity(detailsIntent);
}
});
}
@Override
protected void onPause(){
overridePendingTransition(R.anim.hold, R.anim.push_out_to_right);
super.onPause();
}
private void findViews(){
textViewInfo = findViewById(R.id.textViewInfo);
listViewBooks = findViewById(R.id.listViewBooks);
}
}
Mainactivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText textAuthor;
private EditText textTitle;
private EditText textGenre;
private Button buttonSearch;
private Spinner spinnerGenre;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataStore.Init(getApplicationContext());
textAuthor = findViewById(R.id.editTextAuthor);
textTitle= findViewById(R.id.editTextAuthor);
buttonSearch = findViewById(R.id.buttonSearch);
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenre);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
this,
R.array.book_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
buttonSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filterAuthor = textAuthor.getText().toString();
String filterTitle = textTitle.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("AUTHOR", filterAuthor);
intent.putExtra("TITLE", filterTitle);
intent.putExtra("GENREID", filterGenreId);
startActivity(intent);
}
});
}
}