I'm having an issue trying to build a layout where I have a CollapsingToolbar and a Scrollview
The ScrollView contains two CardViews and a RecyclerView
The CollapsingToolbar consists of an image, a title and no buttons for the moment
Activity Layout
Content Layout (The ScrollView is missing android:fillViewport="true")
With these layouts everything is alright except for the scrolling of course (the parallax doesn't work if I scroll on the cardviews which is annoying)
Here's the Adapter
public class HorariosAdapter extends RecyclerView.Adapter<HorariosAdapter.HorarioViewHolder> {
public static class HorarioViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView horaDesde;
HorarioViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cvHorario);
horaDesde = (TextView) itemView.findViewById(R.id.txtHora);
}
}
List<Horario> horarios;
HorariosAdapter(List<Horario> pHorarios){
this.horarios = pHorarios;
}
#Override
public int getItemCount() {
return horarios.size();
}
#Override
public HorarioViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.rvhorarios, viewGroup, false);
HorarioViewHolder hvh = new HorarioViewHolder(v);
return hvh;
}
#Override
public void onBindViewHolder(HorarioViewHolder horarioViewHolder, int i) {
horarioViewHolder.horaDesde.setText(horarios.get(i).getHoraDesde());
}
}
Over here we have the Activity
public class DetalleActivity extends AppCompatActivity {
final String EXTRA_ITEM = "Complejo";
private TextView txtDireccion;
private ImageView imgThumbnail;
private RecyclerView rvHorarios;
private HorariosAdapter adapter;
public DetalleActivity CustomListView = null;
private Cancha complejoSeleccionado;
private Horario horario;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
complejoSeleccionado = getIntent().getParcelableExtra(EXTRA_ITEM);
setContentView(R.layout.activity_detalle);
setToolbar(complejoSeleccionado.getComplejo().toString());
txtDireccion = (TextView) findViewById(R.id.txtDireccion);
imgThumbnail = (ImageView) findViewById(R.id.imgThumbnail);
txtDireccion.setText(complejoSeleccionado.getDireccion());
String lowerImagen = complejoSeleccionado.getImagen().toLowerCase();
int idImagen = getResources().getIdentifier(lowerImagen, "drawable", getPackageName());
imgThumbnail.setImageResource(idImagen);
rvHorarios = (RecyclerView) findViewById(R.id.rvHorarios);
rvHorarios.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
rvHorarios.setLayoutManager(llm);
CustomListView = this;
horario = new Horario();
horario.initializeData();
adapter = new HorariosAdapter(horario.horarios);
rvHorarios.setAdapter(adapter);
rvHorarios.setNestedScrollingEnabled(false);
}
#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_detalle, 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
switch (id) {
case R.id.action_settings:
return true;
case R.id.action_search:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setToolbar(String titulo)
{
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (complejoSeleccionado.getComplejo().toString() != null) {toolbar.setTitle(titulo);}
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setNavigationIcon(R.drawable.ic_action_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(getApplicationContext(), MainActivity.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
}
});
}
}
I've read about NestedScrollView but I don't think it would solve my problem
I also tried TouchHandlers but to no use
Question
How can I put all these three together and scroll them together?
EDIT 1: I know I shouldn't be using a RecyclerView inside a ScrollView, a possible solution could be to separate them in different tabs?
what you are looking for is parallax effect. This library will give you good idea about how to achieve that
Related
I am trying to dial numbers from my app by clicking on different CardViews but its not working for me.
Everytime i tried adding an intent, the startActivity turns Red and pops out error message "cannot resolve method".
I even tried adding context before the startActivity() But it crashes the app.
I have 4 CardViews to be clicked in order to initiate a call and
I have 3 Java classes: CardViewDataAdapter where the recyclerView Holder was declared, MainActivity and itemObject
In activity_main i used recycler_view. In cardview_row i used card_view and bind it with recycler view.
Please kindly help me, i have googled this problem and also looked it up on stack overflow but no solution found yet.
The error message image
CardViewDataAdapter.java code:
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private List<ItemObject> itemList;
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
// each data item is a string and an image in this case
public ImageView image_view;
public TextView image_name;
private Context context;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
this.image_view = (ImageView) itemLayoutView.findViewById(R.id.image_view);
this.image_name = (TextView) itemLayoutView.findViewById(R.id.image_name);
// Store the context
this.context = context;
// Attach a click listener to the entire row view
itemLayoutView.setOnClickListener(this);
}
// Handles the row being being clicked
#Override
public void onClick(View view) {
if (getPosition() == 0){
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);
} else if (getPosition() == 1){
Toast.makeText(view.getContext(), "position2 = " + getPosition(), Toast.LENGTH_SHORT).show();
} else if (getPosition() == 2){
Toast.makeText(view.getContext(), "position3 = " + getPosition(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(view.getContext(), "position4 = " + getPosition(), Toast.LENGTH_SHORT).show();
}
//context.startActivity(intent);
}
}
// Create new views (invoked by the layout manager)
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardview_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.image_view.setImageResource(itemList.get(position).getPhoto());
viewHolder.image_name.setText(itemList.get(position).getName());
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return this.itemList.size();
}
public CardViewDataAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
}
}
MainActivity.java code:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a GridLayout manager
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter
List<ItemObject> rowListItem = getAllItemList();
mAdapter = new CardViewDataAdapter(MainActivity.this, rowListItem);
mRecyclerView.setAdapter(mAdapter);
}
#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_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.
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Settings Clicked",
Toast.LENGTH_SHORT).show();
return true;
/* } else if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search Clicked",
Toast.LENGTH_SHORT).show();
return true;*/
}
return super.onOptionsItemSelected(item);
}
//Handles the references to items displayed on each cards
private List<ItemObject> getAllItemList() {
List<ItemObject> allItems = new ArrayList<ItemObject>();
allItems.add(new ItemObject("Fire", R.drawable.fire));
allItems.add(new ItemObject("Ambulance", R.drawable.ambulance));
allItems.add(new ItemObject("Police", R.drawable.police));
allItems.add(new ItemObject("AntiSquad", R.drawable.police));
return allItems;
}
}
itemsObject.java code:
public class ItemObject {
private String name;
private int photo;
public ItemObject(String name, int photo) {
this.name = name;
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
}
cardview_row.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- CardView with customized attributes -->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="170dp"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
cardview:cardCornerRadius="20dp"
cardview:cardElevation="90dp"
android:elevation="2dp"
android:background="#drawable/myrect"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
<TextView
android:id="#+id/image_name"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#4757b3"
android:textColor="#android:color/white"
android:fontFamily="sans-serif-condensed"
android:textSize="20sp"
android:textAlignment="center" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Looks like you have a Context issue.
To get the context you need to alter your code to as below:
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:123456789"));
view.getContext().startActivity(callIntent);
Try this :
btnTelephone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Call 1st phone number api
Uri callIntentUri = Uri.parse("tel:"+telephoneStringForCall);
Intent callIntent = new Intent(Intent.ACTION_DIAL, callIntentUri);
startActivity(callIntent);
}
});
and check your views initialisation mb you lost something
I have a scroll view and it give images from database and image view in scroll view create dynamically.I want to when select one of images it display on another activity or bigger.
This is my code:
public class MainActivity extends Activity{
private DatabaseH db;
private Bitmap[] ax;
ImageView im;
int i;
String table="main";
String noeDastor="کار با فایل";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseH(this);
db.useable();
refresher();
LinearLayout yourLayout = (LinearLayout)findViewById(R.id.ll1);
for ( i = 0; i < ax.length; i++) {
im=new ImageView(getApplicationContext());
im.setImageBitmap(ax[i]);
yourLayout.addView(im,700,500);
}
OnClickListener on=new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.putExtra("integer", i);
intent.putExtra("table", table);
intent.putExtra("noeDastor", noeDastor);
startActivity(intent);
}
};
}
#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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void refresher(){
db.open();
int save = db.shomaresh_field(table,noeDastor);
ax = new Bitmap[save];
for (int i = 0; i <save; i++) {
ax[i] = db.retrive(table,noeDastor,i);
}
db.close();
}
Use RecyclerView with LinearLayoutManager and set orientation horizontal like this :
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView rvSlide = (RecyclerView) findViewById(R.id.rvSlide);
rvSlide.setLayoutManager(layoutManager);
Use ImageView as a RecyclerView item and in adapter handle the onClickListner on ImageView then you get what you want.
In your for loop with every add view you should set imageView Id like 0,1,2,etc. as you like
imageView.setId(i);
then you get id by using
imageView.getId();
to be use and find which clicked has been performed but in your imageView.onClickListener callback
I am developing an Android Application for Online Shopping. I have created following view for List of Products using RecyclerView, in that i want to change view on selecting option menu item:
I have created following adapter named ProductAdapter, in that I have implemented code for changing layout in onCreateViewHolder for selecting layout file based on boolean value.
Code of Adapter ProductAdapter:
/***
* ADAPTER for Product to binding rows in List
*/
private class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductRowHolder> {
private List<Product> productList;
private Context mContext;
public ProductAdapter(Context context, List<Product> feedItemList) {
this.productList = feedItemList;
this.mContext = context;
}
#Override
public ProductRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(isProductViewAsList ? R.layout.product_row_layout_list : R.layout.product_row_layout_grid, null);
ProductRowHolder mh = new ProductRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ProductRowHolder productRowHolder, int i) {
Product prodItem = productList.get(i);
// Picasso.with(mContext).load(feedItem.getName())
// .error(R.drawable.ic_launcher)
// .placeholder(R.drawable.ic_launcher)
// .into(productRowHolder.thumbnail);
double price = prodItem.getPrice();
double discount = prodItem.getDiscount();
double discountedPrice = price - (price * discount / 100);
String code = "";
if(prodItem.getCode() != null)
code = "[" + prodItem.getCode() + "] ";
productRowHolder.prodIsNewView.setVisibility(prodItem.getIsNew() == 1 ? View.VISIBLE : View.INVISIBLE);
productRowHolder.prodNameView.setText(code + prodItem.getName());
productRowHolder.prodOriginalRateView.setText("Rs." + new BigDecimal(price).setScale(2,RoundingMode.DOWN));
productRowHolder.prodDiscView.setText("" + new BigDecimal(discount).setScale(2,RoundingMode.DOWN) + "% off");
productRowHolder.prodDiscRateView.setText("Rs." + new BigDecimal(discountedPrice).setScale(2,RoundingMode.DOWN));
productRowHolder.prodOriginalRateView.setPaintFlags(productRowHolder.prodOriginalRateView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
#Override
public int getItemCount() {
return (null != productList ? productList.size() : 0);
}
public class ProductRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//Declaration of Views
public ProductRowHolder(View view) {
super(view);
view.setOnClickListener(this);
//Find Views
}
#Override
public void onClick(View view) {
//Onclick of row
}
}
}
After that i have done code for Changing RecyclerView layout from List to Grid and Vice Versa in onOptionsItemSelected, here i am calling mAdapter.notifyDataSetChanged(); so it will call adapter again and change value.
onOptionsItemSelected:
#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
switch (id) {
case R.id.action_settings:
return true;
case android.R.id.home:
finish();
break;
case R.id.product_show_as_view:
isProductViewAsList = !isProductViewAsList;
supportInvalidateOptionsMenu();
mRecyclerView.setLayoutManager(isProductViewAsList ? new LinearLayoutManager(this) : new GridLayoutManager(this, 2));
mAdapter.notifyDataSetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
I got little bit success like:
Image of Grid layout:
Image of List layout:
BUT NOW WHEN I SCROLL and then CHANGING VIEW is Displaying like:
Grid layout:
List layout:
I dont know why it happens after scrolling. Is there any other way to change view like this.
Today i just saw that this problem is because of ImageView, without it working perfectly.
Help please, You help will be appreciated.
I found solution with the starting of activity I have set LinearLayoutManager like:
mLayoutManager = new LinearLayoutManager(this);
mProductListRecyclerView.setLayoutManager(mLayoutManager);
after that onOptionsItemSelected written like:
case R.id.menu_product_change_view:
isViewWithCatalog = !isViewWithCatalog;
supportInvalidateOptionsMenu();
//loading = false;
mProductListRecyclerView.setLayoutManager(isViewWithCatalog ? new LinearLayoutManager(this) : new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
mProductListRecyclerView.setAdapter(mAdapter);
break;
and changing view in onCreateViewHolder like:
#Override
public ProductRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(isViewWithCatalog ? R.layout.product_row_layout_list : R.layout.product_row_layout_grid, null);
ProductRowHolder mh = new ProductRowHolder(v);
return mh;
}
From Starting to Ending you have to manage isViewWithCatalog variable for displaying which layout first.
In this SDK samples there is a complete example however it uses one layout file for both LayoutManagers
For keeping the scrolling position when switching the layout they used this function
public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
int scrollPosition = 0;
// If a layout manager has already been set, get current scroll position.
if (mRecyclerView.getLayoutManager() != null) {
scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
switch (layoutManagerType) {
case GRID_LAYOUT_MANAGER:
mLayoutManager = new GridLayoutManager(getActivity(), SPAN_COUNT);
mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
break;
case LINEAR_LAYOUT_MANAGER:
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
break;
default:
mLayoutManager = new LinearLayoutManager(getActivity());
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
}
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(scrollPosition);
}
I solved this problem by setting the adapter again to the RecyclerView, after changing the layout manager.
listView.setLayoutManager(new LinearLayoutManager(this));
listView.setAdapter(adapter);
I think after scrolling and changed back to grid view, the first item is not recreated. I solved this by override getItemViewType() and inflate the layout files in onCreateViewHolder accordingly.
I did develop an android project which includes edittext , button and listview . I have a mainActivity which includes these views in it's layout.When user enter a text on Edittext and clikc the buttom ,text will transfer to listview.Up to here, everything is okey , I can do that.Addition to this,I did create class which is extended by ArrayAdapter because I want to optimize application.I want to test application with 1000 text etc ,thanks to this I can optimize my adapter, but I don not know how to I test it ?
public class TodoItemAdapter extends ArrayAdapter<TodoItem> {
int resource;
public TodoItemAdapter(Context context, int resource,List<TodoItem> objects) {
super(context, resource ,objects);
this.resource = resource ;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TodoItem toDoItem = getItem(position);
String toDoTask = toDoItem.task;
String toDoDate = DateFormat.getDateInstance().format(toDoItem.enteringData );
String inflaterService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(inflaterService);
View toDoView = inflater.inflate(this.resource,null);
TextView taskView = (TextView) toDoView.findViewById(R.id.tvTask);
TextView dateView = (TextView) toDoView.findViewById(R.id.tvDate);
taskView.setText(toDoTask);
dateView.setText(toDoDate);
return toDoView;
}
}
public class MyActivity extends Activity {
private ArrayList <TodoItem> todoItems;
private TodoItemAdapter todoArrayAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final EditText etTodo = (EditText) findViewById(R.id.etTodo);
Button btnAddTodo = (Button) findViewById(R.id.btnAddTodo);
ListView lvTodoItems = (ListView) findViewById(R.id.todoListView);
todoItems = new ArrayList<TodoItem>();// line1
todoArrayAdapter = new TodoItemAdapter(this,R.layout.todoitem,todoItems) ;//line2
lvTodoItems.setAdapter(todoArrayAdapter); //line3
//line1,line2 and line3 apply ( DataSource -> Adapter -> AdapterView ) schema.
btnAddTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
todoItems.add(new TodoItem(etTodo.getText().toString()));
todoArrayAdapter.notifyDataSetChanged();
etTodo.setText("");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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);
}
}
You can use Espresso to write Android UI tests like the following:
public void testAdapter() {
for (int i = 0; i < 1000; i++) {
onView(withId(R.id.etTodo))
.perform(typeText("Todo #" + i));
onView(withId(R.id.btnAddTodo))
.perform(click());
}
}
I've got an android app, with a super-class that contains a layout that should be static for each activity, the illustration beneath shows this in a better way rather than my description
This "header" contains a tabBar which contains a ImageButton. I want this header to be static for all the activities in my app. What I tried to do, is to extend my other classes from this superclass. Code for the super class is beneath
public class MySuperClass extends Activity {
MyHorizontalScrollView scrollView;
View menu;
View app;
ImageButton btnSlide;
boolean menuOut = false;
Handler handler = new Handler();
int btnWidth;
Button testClass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = LayoutInflater.from(this);
scrollView = (MyHorizontalScrollView) inflater.inflate(R.layout.horz_scroll_with_list_menu, null);
setContentView(scrollView);
menu = inflater.inflate(R.layout.horz_scroll_menu, null);
app = inflater.inflate(R.layout.horz_scroll_app, null);
ViewGroup tabBar = (ViewGroup) app.findViewById(R.id.tabBar);
ListView listView = (ListView) app.findViewById(R.id.list);
listView = (ListView) menu.findViewById(R.id.list);
ArrayList<MenuItem> menuItems = getMenuItems();
listView.setAdapter(new MenuCustomAdapter(this, menuItems));
btnSlide = (ImageButton) tabBar.findViewById(R.id.BtnSlide);
btnSlide.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
btnSlide.setImageResource(R.drawable.lincolor);
break;
case MotionEvent.ACTION_UP:
btnSlide.setImageResource(R.drawable.lin);
break;
}
return false;
}
});
btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView, menu));
testClass = (Button) app.findViewById(R.id.button1);
testClass.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MySuperClass.this, TestClass.class);
startActivity(intent);
}
});
final View[] children = new View[] { menu, app };
// Scroll to app (view[1]) when layout finished.
int scrollToViewIdx = 1;
scrollView.initViews(children, scrollToViewIdx, new SizeCallbackForMenu(btnSlide));
}
public ArrayList<MenuItem> getMenuItems() {
ArrayList<MenuItem> items = new ArrayList<MenuItem>();
MenuItem m1 = new MenuItem(R.drawable.scroll, "Show history");
items.add(m1);
MenuItem m2 = new MenuItem(R.drawable.right, "Right");
items.add(m2);
return items;
}
/**
* Helper for examples with a HSV that should be scrolled by a menu View's width.
*/
static class ClickListenerForScrolling implements OnClickListener {
HorizontalScrollView scrollView;
View menu;
ImageButton button;
int pressed;
int timeout;
/**
* Menu must NOT be out/shown to start with.
*/
boolean menuOut = false;
public ClickListenerForScrolling(HorizontalScrollView scrollView, View menu) {
super();
this.scrollView = scrollView;
this.menu = menu;
}
#Override
public void onClick(View v) {
Context context = menu.getContext();
int menuWidth = menu.getMeasuredWidth();
// Ensure menu is visible
menu.setVisibility(View.VISIBLE);
if (!menuOut) {
// Scroll to 0 to reveal menu
int left = 0;
scrollView.smoothScrollTo(left, 0);
} else {
// Scroll to menuWidth so menu isn't on screen.
int left = menuWidth;
scrollView.smoothScrollTo(left, 0);
}
menuOut = !menuOut;
}
}
/**
* Helper that remembers the width of the 'slide' button, so that the 'slide' button remains in view, even when the menu is
* showing.
*/
static class SizeCallbackForMenu implements SizeCallback {
int btnWidth;
View btnSlide;
public SizeCallbackForMenu(View btnSlide) {
super();
this.btnSlide = btnSlide;
}
#Override
public void onGlobalLayout() {
btnWidth = btnSlide.getMeasuredWidth();
System.out.println("btnWidth=" + btnWidth);
}
#Override
public void getViewSize(int idx, int w, int h, int[] dims) {
dims[0] = w;
dims[1] = h;
final int menuIdx = 0;
if (idx == menuIdx) {
dims[0] = w - btnWidth;
}
}
}
}
And a test class, which extends this superclass.
public class TestClass extends MySuperClass {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
}
Again how can I make the tabBar static for each activity?
There is no way to achieve this in an Activity-scope. The layout are independent from your Acitvity (well, until you bind them).
The solution to your problem, may be in using a common header layout, kept in a xml file under your layout folder, something like this:
header.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/red"
... />
And include them in your layouts, using the include tag:
my_activity_layout.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
....
.... >
<include layout="#layout/header.xml" android:id="#+id/header" />
<!-- Countinue your layout .... -->
</RelativeLayout>
you can use a TabHost right. by click on each tab you can launch separate activity
http://mfarhan133.wordpress.com/2010/11/17/tablayouttabhost-tutorial-for-android-reusing-layout/
I don't know if that is possible. I will post an alternative solution, which requires a little bit of more code but works, and is a best practice, so if nothing comes up this is the best alternative, probably the only one.
When you are trying to use a certain layout again and again, like the tab bar that you are mentioning, there is the <merge> and <include> functionality in the layout. The basic idea is that you make a layout.xml file that you want to include in other layouts.
This post gives a very good example of how to use it. Simple example of <merge> and <include> usage in Android XML-layouts