I have an activity with a list, whose items are made of an image+text. I need to allow the user to change the view and have a gridview instead of it (whose elements are still made of the same image+text).
The user can do it through an icon menu:
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()== R.id.change_view)
{
// ?
}
}
I tried to just set the new adapter(see below) but it doesn't work..do I have to create a new activity to do that?
if(item.getItemId()== R.id.change_view)
{
setContentView(R.layout.grid_view);
gridViewAdapter = new GridViewAdapter(this,R.layout.bookmark_list_item,MyApp.getItems().findAll());
list.setAdapter(gridViewAdapter);
list.setVisibility(View.VISIBLE);
}
There are several ways you could achieve that.
One solution is to have both the ListView and GridView stacked in a FrameLayout, and when you want to switch between these views, set the visibility GONE to one view and VISIBLE to another, then viceversa.
Put both the ListView and GridView in a ViewFlipper
Or, use a ViewSwitcher
And finally, use just a GridView, but when you want to transition to a list view, set programmatically the number of columns to 1.
I finally resolved with something like this:
For the layout of my activity i have:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ViewStub android:id="#+id/list"
android:inflatedId="#+id/showlayout"
android:layout="#layout/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
<ViewStub android:id="#+id/grid"
android:inflatedId="#+id/showlayout"
android:layout="#layout/grid_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</merge>
then i've defined the layout for the list and the grid (and also for their items), and managed the passage between them inflating the layouts and then by this method:
private void changeView() {
//if the current view is the listview, passes to gridview
if(list_visibile) {
listview.setVisibility(View.GONE);
gridview.setVisibility(View.VISIBLE);
list_visibile = false;
setAdapters();
}
else {
gridview.setVisibility(View.GONE);
listview.setVisibility(View.VISIBLE);
list_visibile = true;
setAdapters();
}
}
the complete code is available in this article: http://pillsfromtheweb.blogspot.it/2014/12/android-passare-da-listview-gridview.html
Related
I am using fragments to update a text view I have so when the person clicks a button the text view moves on to the next question. I'm not sure if I am doing the correct work in one fragment instead of the other. My current screen looks like this:
I will probably have to add some more buttons/widgets to this but should I be adding it into the XML for the fragment or the fragment container?
Here is XML for fragment actions:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_question_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".FragmentActions"
>
<!-- this is where fragments will be shown-->
<FrameLayout
android:id="#+id/question_container1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:scaleType="centerInside" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/questions_yes1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/yes" />
<Button
android:id="#+id/questions_no1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="#string/no" />
</LinearLayout>
</LinearLayout>
And here is the fragment details:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/button_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
tools:context=".FragmentDetails">
<!--Blank Fragment Layout-->
<TextView
android:id="#+id/questions_text_view1"
android:layout_width="match_parent"
android:layout_height="91dp"
android:gravity="center"
android:textAlignment="center"
/>
</FrameLayout>
Updated FragmentDetails
public class FragmentDetails extends Fragment {
private final String TAG = getClass().getSimpleName();
private List<Integer> mQuestionIds;
private int mListIndex;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate the fragment layout
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
//Get a reference to the textView in the fragment layout
final TextView textView = (TextView) rootView.findViewById(R.id.questions_text_view1);
if (mQuestionIds != null) {
textView.setText(mQuestionIds.get(mListIndex));
//Increment the position in the question lisy as long as index is less than list length
if (mListIndex < mQuestionIds.size() - 1) {
mListIndex++;
setmQuestionIds(QuestionList.getQuestions());
setmListIndex(mListIndex);
} else {
//end of questions reached
textView.setText("End of questions");
}
//Set the text resource to display the list item at that stored index
textView.setText(mQuestionIds.get(mListIndex));
}
else {
//Log message that list is null
Log.d(TAG, "No questions left");
}
//return root view
return rootView;
}
public void setmQuestionIds (List < Integer > mQuestionIds) {
this.mQuestionIds = mQuestionIds;
}
public void setmListIndex ( int mListIndex){
this.mListIndex = mListIndex;
}
}
Fragment Actions activity
public class FragmentActions extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_actions);
Button yes = findViewById(questions_yes1);
// Only create new fragments when there is no previously saved state
if (savedInstanceState == null) {
//Create Question Fragment
final FragmentDetails fragmentDetails = new FragmentDetails();
fragmentDetails.setmQuestionIds(QuestionList.getQuestions());
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the list of question Ids for the head fragent and set the position to the second question
//Fragment manager and transaction to add this fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.question_container1, fragmentDetails)
.commit();
}
});
}
}
}
If your Buttons remain the same while the TextView changes, you may add your Buttons to the fragment container.
Remember that, your fragments will be presented inside the FrameLayout of the fragment container. You gotta keep your Buttons, outside the FrameLayout.
Or if you want to have different Buttons for different fragments (Questions, in your case), you can also add the Buttons to the fragments. But in that case, you gotta add them separately to each of the fragments.
I guess there's no right answer to your question. You could try different approaches.
Maybe you could implement the buttons in the fragment container, as #smmehrab pointed out. I see this as a more difficult solution, because when you click on an item from the container you can manage the views of the container, not the fragment's views. You would get NullPointer if I recall correctly. This happens because the context when the button is clicked in the fragment container is different than the context when clicking from within the fragment. So you should implement an interface on the fragment container that listens to clicks, and the fragment catches the click. You could do this, and I actually am doing it in my current app, but I have no choice.
You could instead use Motion Layout (which extends from Constraint Layout) as the root view of your fragment, instead of CardView. This way you could set all the fragment's views with a flat hierarchy (flat hierarchies improves rendering time, so that's an improvement, and you can use CardView as one child) and set the buttons right there, in the Motion Layout (remember, the motion layout would be the fragment's root view). You could set the click listener right there and implement animations between different textViews.
I'm sure there are plenty of other solutions, take this only as a contribution.
If you're unfamiliar with Motion Layout you can just google it, android official documentation about it is great.
I am creating a simple view where on the top I have some elements and below a recyclerView. When I scroll it down, would like to scroll the whole screen, not the only recycler.
I have achieved it with NestedScrollView, however, now the problem appears. Items in the list will be pretty heavy and in this configuration, all the items are bind at the same time(call of onBindViewHolder).
any ideas how to make them recycle and solve this problem?
Here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView 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:background="#android:color/darker_gray"
android:orientation="vertical"
tools:context="com.gkuziel.testkotlin.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/ic_available_stores_default" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test text" />
<android.support.v7.widget.RecyclerView
android:id="#+id/list_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:isScrollContainer="false"
android:nestedScrollingEnabled="false">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Update:
The found a sweet solution: you add a complex header as ItemDecoration, its great cause your adapter can stay untouched, you just add sth like this:
recyclerView.addItemDecoration(dividerItemDecoration);
the only drawback of this solution is i couldn't make this header clickable (in my case it contains another recyclerView), however I know some people achieved it as well.
For this moment I decided implement heterogeneous recyclerview, with 1 instance of header type and the rest of simple row types.
What is important, the header type is fully binded once in HeaderViewHolder constructor and onBindViewHolder looks like this:
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is HeaderViewHolder) {
//do nothing
Log.d("ProductAdapter", "Binding: Header")
} else if (holder is ItemViewHolder) {
Log.d("ProductAdapter", "Binding: " + position.toString())
val searchItem = items!![position - 1]
//here the proper binding is going on
}
}
You can try setting the recyclerview layout manager's method canScrollVertical to false and it won't respond to any touch inner scroll events.
override below method and return false.
boolean canScrollVertically()
here it is how to set.
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Lookup the recyclerview in activity layout
RecyclerView listTest = (RecyclerView) findViewById(R.id.list_test);
// Attach the adapter to the recyclerview to populate items
listTest.setAdapter(adapter);
// Set layout manager to position the items
listTest.setLayoutManager(new LinearLayoutManager(this){
#Override
public boolean canScrollVertically(){
return false;
}
});
// That's all!
}
I am using a DragSortListView and i want a header which will scroll down and up with the list. I have no idea why the header is not scrolling with the list. I use the listview in a fragment and i added the header like this:
public void onViewCreated(View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DragSortListView cursListView = (DragSortListView) view.findViewById(R.id.drag_list);
LayoutInflater inflater = (LayoutInflater) Utils.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
titleLayout = inflater.inflate(R.layout.title_row, null);
cursListView.addHeaderView(titleLayout);
setTitle(titleName, titleValue);
cursListView.setAdapter(cursorAdapter);}
setTitle sets the values for the header and Utils.getContext() return the context of the Application.
public void setTitle(String currency, float value) {
((TextView) titleLayout.findViewById(R.id.titleName)).setText(currency);
((EditText) titleLayout.findViewById(R.id.titleValue)).setText(String.valueOf(value));
((EditText) titleLayout.findViewById(R.id.titleValue)).setImeActionLabel(getString(R.string.convert), EditorInfo.IME_ACTION_DONE);
((EditText) titleLayout.findViewById(R.id.titleValue)).setOnEditorActionListener(convertCurrencies);
restartLoader();
}
Why not create the illusion of a header?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
This way the TextView, in this case, will always stay on top, the ListView can still scroll, which is the desired result if I understand your question correctly.
i think you have first understand what is Header of Footer. Header means that is Always on Top and visible in any Condition same as Footer which is always on bottom and visible.that same concept use for HeaderView and FooterView in listview in android.
So Achive your goal Add one item as header and get it in your Adapterclass getView method and Display it. if there are only one header then at 0 position Your Header available and other position your item available. and it is scroll with your list.
Thats it...
I have this ListView that just needs to show data.
So I don't want to make it clickable.
First I've tried changing XML listview to:
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:clickable="false" >
But it didn't work.
So to solve my problem I set through code:
list.setSelector(android.R.color.transparent);
but I can't believe there's no better solution. Any idea?
Here it is, following the comment:
One way to do so is:
ListView.setOnClickListener(null); OR
You can add android:focusable="false" android:focusableInTouchMode="false" OR
another way in the layout android:listSelector="#android:color/transparent"
Cheers.
Just override isEnabled(position) in your adapter and return false
#Override
public boolean isEnabled(int position) {
return false;
}
override the below method. Return false to say all the items are not clickable.
#override
public boolean areAllItemsEnabled() {
return false;
}
And override below method to return which item is not clickable
public boolean isEnabled(int position) {
if(position == your_item_pos) {
return false;
}
return true;
}
android:listSelector="#android:color/transparent"
it changes the on-clicked color to same as when it is not clicked!
so it appears as if it is plain text...it's a work around.
Just copy this method in your adapter class.
Nothing to do .........
#Override
public boolean isEnabled(int position) {
return false;
}
You may set any condition to make some selected item unclickable.
#Override
public boolean isEnabled(int position) {
//Y for non clickable item
if(data_list.get(position).equalsIgnoreCase("Y"))
{
return false;
}
return true;
}
android:focusable="true"
to any of the item inside listview now listview wont clickable
You could use
yourListView.setOnItemClickListener(null);
Just set android:enabled="false" to the listview and it would do the trick..why to unneccesary keep overriding methods..
Easy way:
listView.setSelector(android.R.color.transparent);
Try this code
In Adapter.getView()
i.setOnClickListener( null );
i.setLongClickable( false );
i.setClickable( false );
In fact,
#override isEnabled() and
setOnClickListener(null)
setClickable(false)
setLongClickable(false)
There are not working for me.
I solve it by override performItemClick
#Override
public boolean performItemClick(View view, int position, long id) {
if(!clickAble){
return false;
}
return super.performItemClick(view,position,id);
}
This is because your ListView item may have a focusable or clickable element, please try the following approach either in XML Layout file or in code:
Add this attribute to the root ViewGroup element of your ListItem XML file (i.e. LinearLayout, RelativeLayout, ...) :
android:descendantFocusability="blocksDescendants"
Add this line to your List Adapter method which is responsible for creating/recycling the list item (most probably getView() or newView()), while parent is the ViewGroup of list item:
parent.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
Only using list.requestFocusFromTouch() in the onResume() method of the containing fragment worked for me.
¯\(ツ)/¯
I have this ListView that just needs to show data. So I don't want to make it clickable.
I have done this in one of my projects, and the sample bellow works fine.
Basically, you just need:
a data source (ArrayList, for example)
a ListView Widget
an ArrayAdapter, in order to bind the data source with the ListView
MainActivity.java
package com.sample.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data source
String[] arrayData = {"Debian", "Ubuntu", "Kali", "Mint"};
// ListView Widget from a Layout
ListView listView = (ListView) findViewById(R.id.mainListView);
// an ArrayAdapter (using a layout as model for displaying the array items)
ArrayAdapter aa = new ArrayAdapter<String>(this, R.layout.main_list_item_layout, arrayData);
// binding the ArrayAdapter with the ListView Widget
listView.setAdapter(aa);
}
}
activity_main.xml
--->Make sure that the ListView Widget is using wrap_content for layout_width and layout_height
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.sample.listview.MainActivity">
<ListView
android:id="#+id/mainListView"
android:layout_width="wrap_content" <---- HERE
android:layout_height="wrap_content" <---- HERE
/>
</LinearLayout>
main_list_item_layout.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainListItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ff0000"
android:textSize="20sp"
>
</TextView>
That's it: a ListView not clickable, just presenting data on the screen.
got myself into a pickle trying to squeeze two ListViews in the same activity. It works, using two separate ListFragments contained in a standard (vertical) LinearLayout.
The problem is, the two lists together are longer than the screen and the second list is therefore partially hidden. Visually, the user expects to drag the whole screen up and unveil the second list. But the two lists have their own internal scrolling and they do not allow for the whole screen to scroll as one piece.
Luckily the lists actually contain very few items (5 each on average). So, theoretically, I could populate a couple of LinearLayouts containers instead. The problem is, the data being displayed by the lists comes from a Cursor and is dynamic. While I am aware of the newView() and bindView() methods of the CursorAdapter, I don't quite understand how I can connect the adapter to the LinearLayout containers instead of ListViews. I.e. how does the CursorAdapter know that it must create 5 row items out of the 5 items it finds in its cursor? Where do I create the loop that iterates over the cursor item and creates the items in the LinearLayout container? And how do I refresh the content of the LinearLayout when the data in the Cursor changes? All the examples I'm finding neatly wrap these issues into the ListView provided by the ListActivity, but I can't use ListViews!
I'm confused!
Manu
EDIT : Here is the xml layout of the (Fragment)Activity when following breceivemail suggestion. Commented out is the original LinearLayout container, prior to breceivemail's suggestion. It should also be noted the the whole activity is in turn contained by a TabHost, but I don't know if that make any difference for the problem at hand.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!--
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
-->
<TextView android:id="#+id/title"
android:textSize="36sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/SelectPlayer"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Playing"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:background="#999999"/>
<fragment android:name="com.myDomain.myApp.PlayerListFragment"
android:id="#+id/playing"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Reserve"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#000000"
android:background="#999999"/>
<fragment android:name="com.myDomain.myApp.PlayerListFragment"
android:id="#+id/reserve"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
Put your listViews in a vertical scroll. You can have scrollable listView inside of a vertical scroll by the following trick. use the following code and enjoy!
private int listViewTouchAction;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
setListViewScrollable(myListView1);
setListViewScrollable(myListView2);
}
private void setListViewScrollable(final ListView list) {
list.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
listViewTouchAction = event.getAction();
if (listViewTouchAction == MotionEvent.ACTION_MOVE)
{
list.scrollBy(0, 1);
}
return false;
}
});
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (listViewTouchAction == MotionEvent.ACTION_MOVE)
{
list.scrollBy(0, -1);
}
}
});
}
listViewTouchAction is a global integer value.