How to make a class the parent with childs - android - android

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

Related

Using RecyclerView in ScrollView with CollapsingToolbar

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

Android - How to create a transition from an item in listview to a whole activity?

What I want is that when the user clicks a list item in a ListView, it converts to a whole activity (as you can see in the following example), but I was not able to find a tutorial explaining this and, actually, I do not know how this movement is called.
In other words, what I want to achieve is:
Increase List Item elevation when it is clicked (as you can see in the right gif)
Expand and transform list item to the next fragment/activity layout that contains detailed information about the clicked item
I have tried a lot of transitions but with no luck. Can anyone help me out to accomplish this?
I build a small sample application that transitions between two activities with the desired effect:
However the transitions in the provided gifs are slightly different. The
transition in the gif on the left side transitions the list element into the content area of the second activity (Toolbar stays in place). In the gif on the right side the transition transforms the list element into the complete screen of the second activity. The following code provides the effect in the left gif. However it should be possible to adapt the solution with minor modifications to achieve the transition in the right gif.
Note this only works on Lollipop. However it is possible to mock a different effect on older devices.
Furthermore the sole purpose of the provided code is to show how it could be done. Don't use this directly in your app.
MainActivity:
public class MainActivity extends AppCompatActivity {
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
ListView listView = (ListView) findViewById(R.id.list_view);
myAdapter = new MyAdapter(this, 0, DataSet.get());
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
startTransition(view, myAdapter.getItem(position));
}
});
}
private void startTransition(View view, Element element) {
Intent i = new Intent(MainActivity.this, DetailActivity.class);
i.putExtra("ITEM_ID", element.getId());
Pair<View, String>[] transitionPairs = new Pair[4];
transitionPairs[0] = Pair.create(findViewById(R.id.toolbar), "toolbar"); // Transition the Toolbar
transitionPairs[1] = Pair.create(view, "content_area"); // Transition the content_area (This will be the content area on the detail screen)
// We also want to transition the status and navigation bar barckground. Otherwise they will flicker
transitionPairs[2] = Pair.create(findViewById(android.R.id.statusBarBackground), Window.STATUS_BAR_BACKGROUND_TRANSITION_NAME);
transitionPairs[3] = Pair.create(findViewById(android.R.id.navigationBarBackground), Window.NAVIGATION_BAR_BACKGROUND_TRANSITION_NAME);
Bundle b = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, transitionPairs).toBundle();
ActivityCompat.startActivity(MainActivity.this, i, b);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:transitionName="toolbar" />
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
DetailActivity:
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
long elementId = getIntent().getLongExtra("ITEM_ID", -1);
Element element = DataSet.find(elementId);
((TextView) findViewById(R.id.title)).setText(element.getTitle());
((TextView) findViewById(R.id.description)).setText(element.getDescription());
// if we transition the status and navigation bar we have to wait till everything is available
TransitionHelper.fixSharedElementTransitionForStatusAndNavigationBar(this);
// set a custom shared element enter transition
TransitionHelper.setSharedElementEnterTransition(this, R.transition.detail_activity_shared_element_enter_transition);
}
}
activity_detail.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:transitionName="toolbar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#abc"
android:orientation="vertical"
android:paddingBottom="200dp"
android:transitionName="content_area"
android:elevation="10dp">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
detail_activity_shared_element_enter_transition.xml (/res/transition/):
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
android:transitionOrdering="together">
<changeBounds/>
<changeTransform/>
<changeClipBounds/>
<changeImageTransform/>
<transition class="my.application.transitions.ElevationTransition"/>
</transitionSet>
my.application.transitions.ElevationTransition:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class ElevationTransition extends Transition {
private static final String PROPNAME_ELEVATION = "my.elevation:transition:elevation";
public ElevationTransition() {
}
public ElevationTransition(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void captureStartValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
#Override
public void captureEndValues(TransitionValues transitionValues) {
captureValues(transitionValues);
}
private void captureValues(TransitionValues transitionValues) {
Float elevation = transitionValues.view.getElevation();
transitionValues.values.put(PROPNAME_ELEVATION, elevation);
}
#Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues, TransitionValues endValues) {
if (startValues == null || endValues == null) {
return null;
}
Float startVal = (Float) startValues.values.get(PROPNAME_ELEVATION);
Float endVal = (Float) endValues.values.get(PROPNAME_ELEVATION);
if (startVal == null || endVal == null || startVal.floatValue() == endVal.floatValue()) {
return null;
}
final View view = endValues.view;
ValueAnimator a = ValueAnimator.ofFloat(startVal, endVal);
a.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
view.setElevation((float)animation.getAnimatedValue());
}
});
return a;
}
}
TransitionHelper:
public class TransitionHelper {
public static void fixSharedElementTransitionForStatusAndNavigationBar(final Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
return;
final View decor = activity.getWindow().getDecorView();
if (decor == null)
return;
activity.postponeEnterTransition();
decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onPreDraw() {
decor.getViewTreeObserver().removeOnPreDrawListener(this);
activity.startPostponedEnterTransition();
return true;
}
});
}
public static void setSharedElementEnterTransition(final Activity activity, int transition) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
return;
activity.getWindow().setSharedElementEnterTransition(TransitionInflater.from(activity).inflateTransition(transition));
}
}
So what are the different parts here:
We have two activities. During the transition four views are transitioned between the activities.
Toolbar: like in the left gif the toolbar doesn't move with the rest of the content.
ListView element View -> becomes the content view of the DetailActivity
StatusBar and NavigationBar Background: If we don't add these views to the set of transitioned views they will fade out and back in during the transition. This however requires to delay the enter transition (see: TransitionHelper.fixSharedElementTransitionForStatusAndNavigationBar)
In the MainActivity the transitioned views are added to the Bundle that is used to start the DetailActivity. Furthermore the transitioned views need to be named (transitionName) in both activities. This can be done in the layout xml as well as programatically.
The default set of transitions, that is used during the shared element transition, affects different aspects of the view(for example: view bounds - see 2). However differences in the elevation of a view are not animated. This is why the presented solution utilizes the custom ElevationTransition.
try this.. Material-Animations
blueIconImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, SharedElementActivity.class);
View sharedView = blueIconImageView;
String transitionName = getString(R.string.blue_name);
ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, sharedView, transitionName);
startActivity(i, transitionActivityOptions.toBundle());
}
});
The Animation you need is called Activity Transitions between shared elements.
By Research I found that you should:
Put your ListView view in a relativeLayout
OnClick, inflate a copy of your renderer
Find the global coordinates for where the renderer sits in
relationship to the parent of the ListView
Add the copied renderer to the RelativeLayout (parent of ListView)
Animate the listView away
On the end of that animate, animate your new renderer
Profit!
public class MainActivity extends Activity {
private RelativeLayout layout;
private ListView listView;
private MyRenderer selectedRenderer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new RelativeLayout(this);
setContentView(layout);
listView = new ListView(this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layout.addView(listView, rlp);
listView.setAdapter(new MyAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// find out where the clicked view sits in relationship to the
// parent container
int t = view.getTop() + listView.getTop();
int l = view.getLeft() + listView.getLeft();
// create a copy of the listview and add it to the parent
// container
// at the same location it was in the listview
selectedRenderer = new MyRenderer(view.getContext());
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(view.getWidth(), view
.getHeight());
rlp.topMargin = t;
rlp.leftMargin = l;
selectedRenderer.textView.setText(((MyRenderer) view).textView.getText());
layout.addView(selectedRenderer, rlp);
view.setVisibility(View.INVISIBLE);
// animate out the listView
Animation outAni = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, -1f, Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f);
outAni.setDuration(1000);
outAni.setFillAfter(true);
outAni.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
ScaleAnimation scaleAni = new ScaleAnimation(1f,
1f, 1f, 2f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
scaleAni.setDuration(400);
scaleAni.setFillAfter(true);
selectedRenderer.startAnimation(scaleAni);
}
});
listView.startAnimation(outAni);
}
});
}
public class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public String getItem(int position) {
return "Hello World " + position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyRenderer renderer;
if (convertView != null)
renderer = (MyRenderer) convertView;
else
renderer = new MyRenderer(MainActivity.this);
renderer.textView.setText(getItem(position));
return renderer;
}
}
public class MyRenderer extends RelativeLayout {
public TextView textView;
public MyRenderer(Context context) {
super(context);
setPadding(20, 20, 20, 20);
setBackgroundColor(0xFFFF0000);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp.addRule(CENTER_IN_PARENT);
textView = new TextView(context);
addView(textView, rlp);
}
} }
Try this spectacular webpage # Getting Started with Activity & Fragment Transitions (part 1). Here they talked about Activity and Fragment Transitions. I have not tried it. My view is that Fragment Transitions is better and less computer intensive, so it's a good start. And you may not need to change Toolbars, you can show/hide them.
Another good SO link is # Animate the transition between fragments, look at the best answer. In that post, they talked about objectAnimator.
Another opinion is about the sample animation you posted, it does not show a smooth animation from one art to another. It is less impressive when the animation is not smooth.
Good luck, have fun, keep us all posted.

How to Implement action buttons with onClick events using GridViewPager

I am implementing android GridviewPager android wear application. with the help of this code sample.
I want to display 2 action buttons, its onClick events, its text, background image. current code is looks like , in round wear emulator
and square emulator
my questions are.
1) How to remove top most black part in round emulator
2) Center image and text in square emulator
3) Perform onClick events on action buttons click
GridPagerAdapter
public class GridPagerAdapter extends FragmentGridPagerAdapter{
private Context mContext;
private ArrayList<GridRow> mRows;
public GridPagerAdapter(Context mContext, FragmentManager fm) {
super(fm);
this.mContext = mContext;
initAdapter();
}
private void initAdapter() {
mRows = new ArrayList<GridRow>();
GridRow row1 = new GridRow();
row1.addPage(new GridPage("", " Add Call", R.drawable.addcall, R.mipmap.ic_launcher));
row1.addPage(new GridPage("", " View Map", R.drawable.view_map, R.mipmap.ic_launcher));
mRows.add(row1);
}
#Override
public Fragment instantiateItem(ViewGroup container, int row, int column) {
Log.d("GridPagerAdapter","in instantiateItem row = "+row+"column = "+column);
return super.instantiateItem(container, row, column);
}
#Override
public Fragment getFragment(int row, int col) {
GridPage page = mRows.get(row).getPage(col);
Log.d("GridPagerAdapter","in getFragment row = "+row+"column = "+col);
CardFragment cardFragment = CardFragment.create(page.getTitle(), page.getText(), page.getIcon());
return cardFragment;
}
#Override
public Drawable getBackgroundForPage(int row, int column) {
GridPage page = mRows.get(row).getPage(column);
return getBackgroundForRow(page.getBackground());
}
#Override
public int getRowCount() {
return mRows.size();
}
#Override
public int getColumnCount(int row) {
return mRows.get(row).getSize();
}
}
Wear Activity
public class WearActivity extends Activity {
private GridViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear);
mPager = (GridViewPager) findViewById(R.id.gridPager);
mPager.setAdapter(new GridPagerAdapter(this, getFragmentManager()));
}
}
Thanks for help in advance
Finally get the answer
1) Add following code in one of xml (rect,round)
<ImageView
android:id="#+id/imgview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="35dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/card1"/>
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:text="#string/hello_square" />
2) Edit instantiateItem method
#Override
public Object instantiateItem(ViewGroup viewGroup, final int row, final int col) {
final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.rect_activity_wear, viewGroup, false);
final TextView textView = (TextView) view.findViewById(R.id.text);
final ImageView imageView = (ImageView) view.findViewById(R.id.imgview);
imageView.setImageResource(carImageIDs[row][col]);
textView.setText(ImageTexts[row][col]);
viewGroup.addView(view);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Wear","Image Click row = "+row+"col = "+col);
}
});
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Wear","text Click row = "+row+"col = "+col);
}
});
return view;
}
Hope it helps someone , happy coding

Drag and Drop in dynamically created GridViews

I have dynamically created tabs, in which I then programatically add a GridView with dragndrop controller. It all works if its only one tab, but if you scroll to the second one, rearrange items and then back, it crashes. I believe its because both tabs are using the same mDragController. It should be fairly easy to fix, any Ideas how to make them use separate controllers?
private DragController mDragController;
private boolean mLongClickStartsDrag = true; // If true, it takes a long click
protected void onCreate(Bundle savedInstanceState) {
...
final TabHost Tabs = (TabHost) findViewById(android.R.id.tabhost);
Tabs.setup();
int count;
for (count =0;count < 2;count++){
...
final int passedTabId = count;
NewTab.setContent(new TabHost.TabContentFactory()
{
public View createTabContent(String tag)
{
...
GridView dynGrid = new GridView(ManageRooms.this);
...
mDragController = new DragController (ManageRooms.this);
dynGrid.setAdapter (new ImageCellAdapter (ManageRooms.this, mDragController));
layout.addView(dynGrid);
return layout;
}
});
Tabs.addTab(NewTab);
}
}
public boolean startDrag (View v) {
v.setOnDragListener (mDragController);
mDragController.startDrag (v);
return true;
}
}
Solution: making an array of mDragControllers;
private DragController[] mDragController = new DragController[3];
and then accessing each one according to the id of the current Tab.

Can't deselect buttons using a custom layout

I'm implementing a container with 3 buttons, added dynamically. When I select one, I want that the other ones are deselected (change drawable). This works when I add the buttons directly to a LinearLayout, which I declared in XML. But when I create a custom layout, which extends LinearLayout, and put my buttons there, it doesn't work anymore (although the code is almost the same). I select one button and the code to deselect the other ones is executed, but they still show the drawable of selected state.
Edit: I always can select the buttons, in both cases. Selection works. What doesn't work in the custom view case is de -selecting the views, or at least the drawable is not changed when the views are deselected.
I reduced the code to the minimal necessary to see the problem.
The activity:
public class TestActivity extends Activity {
private View[] views;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
/////////////////////////////////////////////////////////////////
//uncomment this block to see the working code (without custom layout)
// views = new View[3];
// LinearLayout root = (LinearLayout) findViewById(R.id.container);
// findViewById(R.id.myCustomLayout).setVisibility(View.GONE);
// addButton(root, 0);
// addButton(root, 1);
// addButton(root, 2);
//////////////////////////////////////////////////////////////////
}
private void addButton(final ViewGroup root, final int position) {
View v = new View(this);
LinearLayout.LayoutParams viewLayoutPars = new LinearLayout.LayoutParams(150, 200);
v.setLayoutParams(viewLayoutPars);
v.setBackgroundResource(R.drawable.mybg);
if (position == 0) {
v.setSelected(true);
}
root.addView(v);
views[position] = v;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (View view : views) {
view.setSelected(false);
}
v.setSelected(true);
root.invalidate();
}
});
}
}
The layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.test.MyCustomLayout
android:id="#+id/myCustomLayout"
xmlns:dg="http://schemas.android.com/apk/res/com.test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
My custom layout:
public class MyCustomLayout extends LinearLayout {
private Context context;
private View[] views;
public MyCustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
views = new View[3];
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
addButton(0);
addButton(1);
addButton(2);
}
private void addButton(final int position) {
View v = new View(context);
LinearLayout.LayoutParams viewLayoutPars = new LinearLayout.LayoutParams(150, 200);
v.setLayoutParams(viewLayoutPars);
v.setBackgroundResource(R.drawable.mybg);
if (position == 0) {
v.setSelected(true);
}
addView(v);
views[position] = v;
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (View view : views) {
view.setSelected(false);
}
v.setSelected(true);
invalidate();
}
});
}
}
The drawable (mybg):
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/selected" />
<item android:drawable="#drawable/not_selected" />
</selector>
The images are 2 harmless squares selected.png and not_selected.png with different color.
Thanks in advance.

Categories

Resources