I'm relatively new to the Android development and encountered the following problem:
I have a ListView with a corresponding ArrayAdapter which delivers simple item views. The item views are structured in a simple RelatveLayout manner revealing some behavior if clicked or long-pressed using the callback methods of OnItemClickListener and OnItemLongClickListener. This works fine so far. However, if I add an ImageButton to the item view with a corresponding onClick-callback, the original listener-methods on the item view itself don't work any more. The items in the ListView can't be selected any more as well. Why?
public class ProfileActivity extends Activity implements ActionBar.TabListener {
private static final String DEBUG_TAG = ProfileActivity.class
.getSimpleName();
private XMLBinder profilesDao;
private Config config;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getActionBar().setSubtitle("Game Profiles");
// load profiles:
profilesDao = new XMLBinder(this);
try {
config = profilesDao.deserialize(Config.class,
R.raw.default_profiles);
} catch (Exception e) {
if (BuildConfig.DEBUG) {
Log.e(DEBUG_TAG, e.toString());
}
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager(),
config.getCategories());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
// SharedPreferences pref = getSharedPreferences("AGT",
// Context.MODE_PRIVATE);
// SharedPreferences.Editor prefEditor = pref.edit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.profile, 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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private List<Category> categories;
/** */
public SectionsPagerAdapter(final FragmentManager fm,
final List<Category> categories) {
super(fm);
this.categories = categories;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
final List<Profile> profiles = config.getCategories().get(position)
.getProfiles();
return PlaceholderFragment.newInstance(position + 1, profiles,
ProfileActivity.this);
}
#Override
public int getCount() {
// Show x total pages.
return this.categories.size();
}
#Override
public CharSequence getPageTitle(int position) {
return categories.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements
OnItemClickListener {
private List<Profile> list;
private ProfilesAdapter profilesAdapter;
private Context context;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*
* #param list
*/
public static PlaceholderFragment newInstance(int sectionNumber,
List<Profile> list, Context context) {
final PlaceholderFragment fragment = new PlaceholderFragment(list,
context);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
super();
}
/** */
public PlaceholderFragment(List<Profile> list, Context context) {
this();
this.list = list;
this.context = context;
this.profilesAdapter = new ProfilesAdapter(this.context,
R.layout.view_profile, this.list);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_profile,
container, false);
// Configure the ListView with Adapter
final ListView profilesView = (ListView) rootView
.findViewById(R.id.profilesView);
profilesView.setAdapter(profilesAdapter);
// #TODO:
// profilesView.setDivider();
// profilesView.setEmptyView(emptyView);
profilesView.setOnItemClickListener(this);
profilesAdapter.notifyDataSetChanged();
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (view != null) {
final GameProfile selectedProfile = (GameProfile) parent
.getItemAtPosition(position);
final Intent intent = new Intent(this.context,
ChessClockActivity.class);
intent.putExtra(GameProfile.INTENT_EXTRA_SELECTED_PROFILE,
selectedProfile);
startActivity(intent);
}
}
}
/**
* #author Andy
*
*/
public static class ProfilesAdapter extends ArrayAdapter<Profile> {
private Context context;
private List<Profile> profiles;
/** */
public ProfilesAdapter(Context context, int resource,
List<Profile> profiles) {
super(context, resource, profiles);
this.context = context;
this.profiles = profiles;
}
#Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
View profileView = convertView;
if (null == profileView) {
final LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
profileView = inflater.inflate(R.layout.view_profile, null);
}
final TextView name = (TextView) profileView
.findViewById(R.id.profile_name);
name.setText(profiles.get(position).getTitle());
final TextView hint = (TextView) profileView
.findViewById(R.id.profile_desc);
hint.setText(profiles.get(position).getHint());
hint.setMaxLines(1);
hint.setEllipsize(TruncateAt.END);
return profileView;
}
}
}
use
android:descendantFocusability="blocksDescendants"
android:focusable="false"
hope it helps
Dont know if it's gonna help
ImageView yourImg=(ImageView).findViewById(R.id.icon);
yourImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// things you want to do
}
});
Related
First of all, I'm sorry for my english, but I need your help.
I got a recyclerView gallery with photos and option to show the selected photo in another activity.
I`m trying to share an image that activity to somewhere, e.g. email, but I receive an empty message with no image.
Could you help me to find out, what am I doing wrong?
Below is the code of gallery activity and single image activity.
Thank you for answers.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
public static String getURLForResource(int resourceId) {
return Uri.parse("android.resource://" + R.class.getPackage().getName() + "/" + resourceId).toString();
}
public static String IMGS[];
public static String MAYF[] = {
"file:///android_asset/mayf1.jpg",
"file:///android_asset/mayf2.gif",
"file:///android_asset/mayf3.jpg",
"file:///android_asset/mayf4.jpg",
"file:///android_asset/mayf5.gif",
"file:///android_asset/mayf6.gif",
"file:///android_asset/mayf7.jpg",
"file:///android_asset/mayf8.jpg",
"file:///android_asset/mayf9.jpg",
"file:///android_asset/mayf10.jpg"
};
public static String APRF[] = {
"file:///android_asset/apr1.jpg",
"file:///android_asset/apr2.gif",
"file:///android_asset/apr3.jpg",
"file:///android_asset/apr4.jpg",
"file:///android_asset/apr5.gif",
"file:///android_asset/apr6.gif",
"file:///android_asset/apr7.jpg",
"file:///android_asset/apr8.jpg",
"file:///android_asset/apr9.jpg",
"file:///android_asset/apr10.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (StartingActivity.count == 1)
IMGS = Arrays.copyOf(APRF, APRF.length);
else if (StartingActivity.count == 2) {
IMGS = Arrays.copyOf(MAYF, MAYF.length);
} else {
Toast.makeText(getBaseContext(), "not filled yet",
Toast.LENGTH_LONG).show();
}
for (int i = 0; i < IMGS.length; i++) {
ImageModel imageModel = new ImageModel();
imageModel.setName("Image " + i);
imageModel.setUrl(IMGS[i]);
data.add(imageModel);
}
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
intent.putExtra("superUri", IMGS[position]);
startActivity(intent);
}
}));
}
#Override
public void onBackPressed() {
super.onBackPressed();
StartingActivity.count = 0;
}
}
This part is a part of a single image.
public class DetailActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private ShareActionProvider mShareActionProvider;
public ArrayList<ImageModel> data = new ArrayList<>();
int pos;
String shPos;
Toolbar toolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
// setSupportActionBar(toolbar);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
shPos = getIntent().getStringExtra("superUri");
setTitle("Открытки");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
//setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
// Fetch and store ShareActionProvider
// Return true to display 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void onShClick(MenuItem item) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(shPos));
shareIntent.setType("image/*");
startActivity(shareIntent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageModel> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageModel> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUri());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
#Override
public CharSequence getPageTitle(int position) {
return data.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
final ImageView imageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).into(imageView);
return rootView;
}
}
}
Here is an example of trying to share image via gmail. I can see the image "attached", but can`t open it. Another email receives an empty message with no attachment inside.
sharing example
From MainActivity when i goto HolidayActivity by using explicit intent i am able to see the LisView is populated with distinct elements within the fragment, After pressing back button i again goto MainActivity and when i again try to open HolidayActivity the ListView is populated again with duplicate elements, I have used LoaderManager, so when device is rotated there is no duplicate elements, the problems occurs only when i switch between activities as described above. I have also tried to Override methos onKeyDown() and onBackPresses() but nothing seems to work out. Point to be noted out here is that i am fetching the list items from server.
HolidayActivity.java
public class HolidaysActivity extends AppCompatActivity {
public static String HOLIDAY_REQUEST_URL;
public static holidayAdapter adapter;
public static final String LOG_TAG = HolidaysActivity.class.getSimpleName();
public static Context mcontext ;
public static Activity activity = null;
public static int list_id;
public static ListView listView_holiday;
/**
* The {#link PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link FragmentStatePagerAdapter}.
*/
private static boolean studentLogin = false;
private static boolean employeeLogin = false;
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
mcontext = this;
activity = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holidays);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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(container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
HolidaysActivity.this.finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
super.onBackPressed();
activity.finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_holidays, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<holidays>> {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.holidays_list, container, false);
// condition for switching to student login in TabWidget for registering complain
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
HOLIDAY_REQUEST_URL = "http://192.168.43.26/fetch_restricted_holidays.php";
listView_holiday = (ListView)rootView.findViewById(R.id.list);
adapter = new holidayAdapter(activity,new ArrayList<holidays>(),0);
listView_holiday.setAdapter(adapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(1,null,this);
}
//condition for switching to employee login in Tabwidget for registering complain
else {
}
return rootView;
}
#Override
public Loader<List<holidays>> onCreateLoader(int id, Bundle args) {
return new HolidayLoader(activity,HOLIDAY_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<holidays>> loader, List<holidays> holidays) {
adapter.clear();
if(holidays!=null && !holidays.isEmpty()){
adapter.addAll(holidays);
adapter.notifyDataSetChanged();
}
}
#Override
public void onLoaderReset(Loader<List<holidays>> loader) {
adapter.clear();
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Gazetted Holidays";
case 1:
return "Restricted Holidays";
}
return null;
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout complainLinearLayout = (LinearLayout)findViewById(R.id.complain_LinearLayout);
complainLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent complainIntent = new Intent(MainActivity.this, Complain.class);
startActivity(complainIntent);
}
});
LinearLayout holiday = (LinearLayout)findViewById(R.id.holidays_LinearLayout);
holiday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity( new Intent(MainActivity.this, HolidaysActivity.class));
}
});
}
}
I have a fragment (AdvertismentFragment) that contains two tabs, now the thing is i need to open in the layout of the first tab a fragment as shown bellow (AdsFragment).. now when i click for the first time the fragment is displayed within the tab and all its content, but when i leave this fragment and return it doesn't display the fragment inside the tab...
here is the code of one of the tabs:
public class AdsFragment extends Fragment {
public AdsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_ads, container, false);
getFragmentManager().beginTransaction().replace(R.id.attending_layout,EventsFragment.newInstance("all","upcoming")).commit();
return v;
}
}
what should i do then ???
here is the fragment that holds the two tabs:
public class AdvertisementFragment extends Fragment implements ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener {
private TabHost tabHost;
private ViewPager viewPager;
private View v;
public AdvertisementFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_advertisement, container, false);
initViewPager();
initTabHost();
return v;
}
/**
* Initialize the {#link TabHost} {#code tabHost}.
*/
private void initTabHost() {
tabHost = ((TabHost) v.findViewById(R.id.tabHost));
tabHost.setup();
/**
* {#code tabName} {#link String} will hold the tab names.
*/
String tabName[] = { "Ads","Videos"};
for (int i = 0; i < tabName.length; i++) {
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec(tabName[i]);
tabSpec.setIndicator(tabName[i]);
tabSpec.setContent(new FakeContent(getActivity()));
tabHost.addTab(tabSpec);
}
/**
* Change the Text color associated with the {#link android.widget.TabWidget}.
*/
for (int tabIndex = 0; tabIndex < tabHost.getTabWidget().getTabCount(); tabIndex++) {
View tab = tabHost.getTabWidget().getChildTabViewAt(tabIndex);
TextView t = (TextView) tab.findViewById(android.R.id.title);
t.setTextColor(Color.parseColor("#1976D2"));
t.setAllCaps(false);
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(),"Roboto-Medium.ttf");
t.setTypeface(typeface);
tab.setBackgroundResource(R.drawable.apptheme_tab_indicator_holo);
}
tabHost.getTabWidget().setDividerDrawable(null);
tabHost.setOnTabChangedListener(this);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onTabChanged(String s) {
int selectedItem = tabHost.getCurrentTab();
viewPager.setCurrentItem(selectedItem);
/**
* Using {#link HorizontalScrollView} {#code horizontalScrollView}
* we can display page by page to the user while pressing the tab.
*/
HorizontalScrollView horizontalScrollView = (HorizontalScrollView) v.findViewById(R.id.h_scroll_view);
View tabView = tabHost.getCurrentTabView();
/**
* Allow the Scroll to be smooth.
*/
int scrollPos = tabView.getLeft() - (horizontalScrollView.getWidth() - tabView.getWidth() / 2);
horizontalScrollView.smoothScrollTo(scrollPos, 0);
}
/**
* Create and return the content of each tab created.
*/
public class FakeContent implements TabHost.TabContentFactory {
private Context context;
public FakeContent(Context context) {
this.context = context;
}
/**
* Callback to make the tab contents
*
* #param tag Which tab was selected.
* #return The view to display the contents of the selected tab.
*/
#Override
public View createTabContent(String tag) {
View fakeView = new View(context);
fakeView.setMinimumHeight(0);
fakeView.setMinimumWidth(0);
return fakeView;
}
}
private void initViewPager() {
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
//viewPager.setPageTransformer(true, new AnimationUtilities.DepthPageTransformer());
List<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(new AdsFragment());
fragmentList.add(new VideoFragment());
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(((MainActivity)getActivity()).getFragmentManager(), fragmentList);
viewPager.setAdapter(myFragmentPagerAdapter);
viewPager.setOnPageChangeListener(this);
}
}
I am a beginner to android applications,I working around tab+swipe application,
my main class is like belove. please help me out.
public class MainScreenViewActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private static String list_display_data1 = "item#sec1";
private static String list_display_data2 = "item#sec2";
private static String list_display_data3 = "item#sec3";
private static View rootView;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen_view);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
/*mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// When swiping between pages, select the
// corresponding tab.
getActionBar().setSelectedNavigationItem(position);
}
});*/
}
#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_screen_view, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = null;
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(
R.layout.fragment_main_screen_view_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
dummyTextView.setVisibility(View.INVISIBLE);
if(dummyTextView.getVisibility() == View.VISIBLE){
ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
}
else{
Log.d("", "");
}
//ListView sessionList = (ListView) rootView.findViewById(R.id.session_list);
//initListView(getActivity(), sessionList, list_display_data1, 30, android.R.layout.simple_list_item_1);
return rootView;
}
}
public static void initListView(Context context, ListView listView,String prefix, int numItems, int layout ){
// By using setAdpater method in listview we an add string array in list.
String[] arr = new String[numItems];
for(int i = 0; i< arr.length; i++){
arr[i] = prefix + (i +1);
}
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Context context = view.getContext();
String msg = "item[" + position + "]= " + parent.getItemIdAtPosition(position);
Toast.makeText(context, msg, 1000).show();
System.out.println(msg);
}
});
}
}
in onCreateView of dummySectionFragment how to add different list view. I just able to work on visibility of view.
You should Add Fragments to your viewpager for different page for different Tabs.
I am using an ActionBar with three Tabs. I also have a item in the ActionBar. I want to react on a click on these item different depending on the selected tab. How can I do this?
Code from my activity:
public class CreateProjectManually extends FragmentActivity implements ActionBar.TabListener {
private static ArrayList<String> buildingList;
private static ArrayList<String> roomList;
private static ArrayList<String> deviceList;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {#link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_project_manually);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// set the app icon as an action to go home
actionBar.setDisplayHomeAsUpEnabled(true);
//enable tabs in actionbar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
/**
* Actionbar
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_save:
//TODO Speichern implementieren
Toast.makeText(getBaseContext(), "Speichern",Toast.LENGTH_LONG).show();
break;
case R.id.menu_add:
//TODO Eintrag hinzufügen implementieren
if(getItem()==0){
}
break;
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, CreateProject.class);
intent.putExtra("Uniqid","From_CreateProjectManually_Activity");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return true;
default:
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_project_manually, menu);
return true;
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment building_fragment = new BuildingFragment();
Fragment room_fragment = new RoomFragment();
Fragment device_fragment = new DeviceFragment();
Bundle args = new Bundle();
switch(i){
case 0:
args.putInt(BuildingFragment.ARG_SECTION_NUMBER, i);
building_fragment.setArguments(args);
return building_fragment;
case 1:
args.putInt(RoomFragment.ARG_SECTION_NUMBER, i);
room_fragment.setArguments(args);
return room_fragment;
case 2:
args.putInt(DeviceFragment.ARG_SECTION_NUMBER, i);
device_fragment.setArguments(args);
return device_fragment;
default: return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.building).toUpperCase();
case 1: return getString(R.string.room).toUpperCase();
case 2: return getString(R.string.devices).toUpperCase();
}
return null;
}
}
/**
* A fragment representing building structure
*/
public static class BuildingFragment extends Fragment {
public BuildingFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listviews, container, false);
ListView listView = (ListView) view.findViewById(R.id.listviewfragment);
buildingList = new ArrayList<String>();
ListAdapter listenAdapter = new ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, buildingList);
// Assign adapter to ListView
listView.setAdapter(listenAdapter);
return view;
}
}
/**
* A fragment representing room structure
*/
public static class RoomFragment extends Fragment {
public RoomFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listviews, container, false);
ListView listView = (ListView) view.findViewById(R.id.listviewfragment);
roomList = new ArrayList<String>();
ListAdapter listenAdapter = new ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, roomList);
// Assign adapter to ListView
listView.setAdapter(listenAdapter);
return view;
}
}
/**
* A fragment representing device structure
*/
public static class DeviceFragment extends Fragment {
public DeviceFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listviews, container, false);
ListView listView = (ListView) view.findViewById(R.id.listviewfragment);
deviceList = new ArrayList<String>();
ListAdapter listenAdapter = new ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, deviceList);
// Assign adapter to ListView
listView.setAdapter(listenAdapter);
return view;
}
}
}
I guess you had the answer all along:
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}