How to make clickable image in horizontal scroll view? - android

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

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

How to test a android project which includes edittext ,button and listview?

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());
}
}

How to make a listview(already created) clickable (Android)?

I made a list and now I want when the user clicks an item, it opens a new screen showing the PKMN data. Here's my code:
Kanto.class
public class Kanto extends ActionBarActivity {
//fasendu listaa = making list
ListView listView; //criandu var = making variable
String[] pokemonsKanto = {
"#1 Bulbasaur", "#2 Ivysaur", "#3 Venusaur"
}; //lista = list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kanto);
//continuandu a lista = the other part to the list work
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> array = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, pokemonsKanto);
listView.setAdapter(array);
//lista cabada = finished
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.kanto, 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();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
activity_kanto.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Kanto">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
How can I do that? Sorry, I'm a completely newbie .
Now you just have to set an onItemClickListener to your ListView, like this:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//create an Intent to your new `Activity` with PKMN data
Intent pkmnActivityIntent = new Intent(Kanto.this, YourPKMNActivity.class);
//pass your pkmn number and name (from your `String` array) in the `Intent`, so it can be shown in the new `Activity`
pkmnActivityIntent.putExtra("name",pokemonsKanto[position] );
//start your new Activity
startActivity(pkmnActivityIntent );
}
});
This listener is activated when the user clicks an item in your list. You can set it right after listview.setAdapter() method.
Edit: Do not forget to declare your new Activity on your manifest.xml file.
Then in your new Activity, just get the pkmn name by using:
String pkmnName = getIntent().getStringExtra("name");
Now you can show your pkmnName in a TextView or something.
You need to add a listener to the items of the list,for example I will give you how to show the text of the item in an alert dialog (you can put the title of the item in a string to pass it in intent rather than display it in an alert dialog) :
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//The title of the Item is recovered in a String
String item = (String) listView.getAdapter().getItem(position);
AlertDialog.Builder adb = new AlertDialog.Builder(kanto.this);
//The title of the alert Dialog
adb.setTitle("Your Item");
//The name of the Item
adb.setMessage("You have selected : "+item);
//the OK button
adb.setPositiveButton("Ok", null);
//show the alert dialog
adb.show();
}
});

expandable listview android change layout on click

I have android project where I have to change layout of last exxpanded group (which will collapse) and the group which is clicked. onGroupClick method i have :
int cnt=list.getChildCount();
//set layout to all groups (for closed group)
for(int i = 0; i < cnt; i`enter code here`++){
View group = adapter.getGroupView(i, false,
null, list);
LinearLayout childLayout = (LinearLayout) group.findViewById(R.id.newsLayout); childLayout.setBackgroundResource(R.layout.group_layout_shape);
}
// set layout of clicked group
LinearLayout groupLayout = (LinearLayout) v.findViewById(R.id.newsLayout);
groupLayout.setBackgroundResource(R.layout.group_layout_opened_shape);`enter code here`
it changes layout of clicked group(which will expand), but doesn't change layout of group, that colapses :( can ayone help me
You should not use this method because it is used only for the pictures, colors, layouts to be used inflater, which has a very interesting method
inflate(R.layout.childLayout, ParentView, true);
where you put first the layer you want to inflate, the second - a parent that will contain child and the third - a boolean variable must be true to inflate held.
Example in Activity:
public class MainActivity extends ActionBarActivity {
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout parentView= (RelativeLayout) findViewById(R.id.mainLayout);
View v = (View) inflater.inflate(R.layout.child_layout, parentView, true);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

How to make a class the parent with childs - 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

Categories

Resources