Viewpager in Dialog? - java

I'm trying to have a dialog where you can click a "next" button to swipe right to the next screen. I am doing that with a ViewPager and adapter:
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter();
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
However, I get a NullPointerException saying that pager is null. Why is this happening? Here is the Page Adapter class:
public class MyPageAdapter extends PagerAdapter {
public Object instantiateItem(ViewGroup collection, int position) {
int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
Here's my layout for the DIALOG:
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Let me know on how to avoid this situation.
PS: Each of the layouts that should be in the view pager look like this, just diff. text:
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/voice2"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Slide 1!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_gravity="center"
android:textSize="50sp" />
</RelativeLayout>

Without Using Enum Class
You should call findViewById on dialog. so for that you have to add dialog before findViewById..
Like this,
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
After solving your null pointer exception the other problem's solution here, if you wont use enum class you can use below code...
MainActivity.java
package demo.com.pager;
import android.app.Dialog;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.voicedialog);
dialog.setCanceledOnTouchOutside(false);
MyPageAdapter adapter = new MyPageAdapter(MainActivity.this);
ViewPager pager = (ViewPager) dialog.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
dialog.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="demo.com.pager.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
MyPageAdapter.java
package demo.com.pager;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class MyPageAdapter extends PagerAdapter {
Context mContext;
int resId = 0;
public MyPageAdapter(Context context) {
mContext = context;
}
public Object instantiateItem(ViewGroup collection, int position) {
/* int resId = 0;
switch (position) {
case 0:
resId = R.id.voice1;
break;
case 1:
resId = R.id.voice2;
break;
}
return collection.findViewById(resId);*/
LayoutInflater inflater = LayoutInflater.from(mContext);
switch (position) {
case 0:
resId = R.layout.fragment_blue;
break;
case 1:
resId = R.layout.fragment_pink;
break;
}
ViewGroup layout = (ViewGroup) inflater.inflate(resId, collection, false);
collection.addView(layout);
return layout;
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
FragmentBlue.java
package demo.com.pager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
public class FragmentBlue extends Fragment {
private static final String TAG = FragmentBlue.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blue, container, false);
return view;
}
}
fragment_blue.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:background="#4ECDC4">
</RelativeLayout>
voicedialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Please check and reply.

Using Enum Class
Try this code, This is working if any doubt ask again. Happy to help.
MainActivity.java
package demo.com.dialogdemo;
import android.app.Dialog; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupUIComponents();
setupListeners();
}
private void setupUIComponents() {
button = (Button) findViewById(R.id.button);
}
private void setupListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogItemDetails = new Dialog(MainActivity.this);
dialogItemDetails.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogItemDetails.setContentView(R.layout.dialoglayout);
dialogItemDetails.getWindow().setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT));
ViewPager viewPager = (ViewPager) dialogItemDetails.findViewById(R.id.viewPagerItemImages);
viewPager.setAdapter(new CustomPagerAdapter(MainActivity.this));
dialogItemDetails.show();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dialog" />
</RelativeLayout>
ModelObject1.java
public enum ModelObject1 {
RED(R.string.red, R.layout.fragment_one),
BLUE(R.string.blue, R.layout.fragment_two);
private int mTitleResId;
private int mLayoutResId;
ModelObject1(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
CustomPagerAdapter.java
package demo.com.dialogdemo;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by rucha on 26/12/16.
*/
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject1 modelObject = ModelObject1.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject1.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject1 customPagerEnum = ModelObject1.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
dailoglayout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtHeaderTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="ITEM IMAGES"
android:textStyle="bold" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerItemImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" />
</RelativeLayout>
fragmentone.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="one"/>
</LinearLayout>

Related

size of recycler view item changes when user scrolls down and up

I am working on a chat functionality to implement in my app. The purpose is that when a message comes from another user, the message item will align parent's start and when the user sends a message, it will align to the end. The send button on upper left corner simulates the other user sending a message. The problem is that when items recycles, some of them mathes the width of parent layout. I do not really understand why this happens and how to fix it. Thanks in advance...
package com.example.messageapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Context;
import android.database.Observable;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button sendBtn;
Button otherSendBtn;
EditText editText;
RecyclerView recyclerView;
MessagesAdapter adapter;
List<ChatMessage> messageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageList=new ArrayList<>();
sendBtn=findViewById(R.id.sendBtn);
otherSendBtn=findViewById(R.id.otherSendBtn);
editText=findViewById(R.id.editText);
recyclerView=findViewById(R.id.recyclerView);
adapter=new MessagesAdapter(this,messageList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
for(int i=0; i<4; i++){
if(i%2==0){
messageList.add(new ChatMessage("from him","self"));
}else{
messageList.add(new ChatMessage("from me","other"));
}
adapter.notifyItemInserted(messageList.size()-1);
}
otherSendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
messageList.add(new ChatMessage("random","other"));
adapter.notifyItemInserted(messageList.size()-1);
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String txt=editText.getText().toString();
messageList.add(new ChatMessage(txt, "self"));
adapter.notifyItemInserted(messageList.size()-1);
editText.setText("");
hideKeyboardFrom(MainActivity.this, view);
}
});
}
public static void hideKeyboardFrom(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
model class for messages
package com.example.messageapp;
public class ChatMessage {
public String text;
public String user;
public ChatMessage(String text, String user) {
this.text = text;
this.user = user;
}
}
recycler view adapter
package com.example.messageapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MessagesAdapter extends RecyclerView.Adapter {
Context context;
List<ChatMessage> messages;
public void setMessages(List<ChatMessage> messages) {
this.messages = messages;
}
public MessagesAdapter(Context context, List<ChatMessage> messages) {
this.context = context;
this.messages = messages;
}
private static class MessageViewHolder extends RecyclerView.ViewHolder{
TextView textView;
RelativeLayout relativeLayout;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
textView=itemView.findViewById(R.id.messageTextView);
relativeLayout=itemView.findViewById(R.id.item_parent);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(context).inflate(R.layout.message_item,parent,false);
return new MessageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChatMessage message=messages.get(position);
((MessageViewHolder) holder).textView.setText(message.text);
RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) ((MessageViewHolder) holder).relativeLayout.getLayoutParams();
if(message.user.equals("self")){
params.addRule(RelativeLayout.ALIGN_PARENT_END);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.teal_200));
}else{
params.addRule(RelativeLayout.ALIGN_PARENT_START);
((MessageViewHolder) holder).relativeLayout.setBackgroundColor(context.getResources().getColor(R.color.purple_200));
}
((MessageViewHolder) holder).relativeLayout.setLayoutParams(params);
}
#Override
public int getItemCount() {
return messages.size();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp">
<RelativeLayout
android:id="#+id/item_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/teal_700">
<TextView
android:padding="10dp"
android:id="#+id/messageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/otherSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"
android:layout_centerHorizontal="true"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/otherSendBtn"
tools:listitem="#layout/message_item"/>
<RelativeLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toStartOf="#+id/sendBtn"
android:layout_marginEnd="5dp"/>
<Button
android:background="#drawable/ic_baseline_send_24"
android:id="#+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</RelativeLayout>

Android Studio Grid View doesn't show when I run the app

I created a Java class that should display something like this:
But this is what I get when I run the app:
It doesn't show what I wanted and Android Studio doesn't show any error in Logcat, so I don't know why it's not working.
This is the code for the class SetsActivity:
package com.example.myquiz;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.Toolbar;
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.set_toolbar);
//setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridview);
SetsAdapter adapter = new SetsAdapter(2);
sets_grid.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
{
SetsActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
}
I also created an adapter class SetsAdapter so I'm gonna post the code for it as well:
package com.example.myquiz;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
} else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(),QuestionActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.setNo_tv)).setText(String.valueOf(position + 1));
return view;
}
}
And here is the code for the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SetsActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/set_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
></androidx.appcompat.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sets"
android:textSize="26sp"
android:textStyle="bold"
android:padding="16dp" />
<GridView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/sets_gridview"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="16dp"
android:verticalSpacing="16dp"
android:padding="16dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
></GridView>
</LinearLayout>
Here is the code for the XML file set_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center"
android:background="#drawable/round_corner"
android:backgroundTint="#FFC3C3"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/setNo_tv"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="45sp"></TextView>
</LinearLayout>
The getCount() method in the SetsAdapter should return numOfSets not 0.
#Override
public int getCount() {
return numOfSets;
}

How to implement SelectionTracker in Java not Kotlin

On Android, I want to users to be able to select multiple rows from a list. I read that I can use SelectionTracker with a RecyclerView to enable list-item selection.
But all the code examples are in Kotlin. Are there any examples of SelectionTracker in Java?
Here is a settings menu that allows the user to choose multiple settings. To begin the selection, the user has to long press any setting. Then they can tap any setting to choose more.
Activity
package com.locuslabs.android.sdk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.locuslabs.android.sdk.api.ConfigurationExperiments;
import com.locuslabs.android.sdk.api.MapExperiments;
import com.locuslabs.android.sdk.api.MapViewExperiments;
import com.locuslabs.android.sdk.api.PositionExperiments;
import com.locuslabs.android.sdk.api.VenueExperiments;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class SettingsActivity extends Activity {
private static final String TAG = "SettingsActivity";
SelectionTracker<Long> selectedSettingTracker;
private RecyclerView settingsRecyclerView;
private List<String> listOfUsableApis;
private ApiSettings mApiSettings;
private void setApiSettings(List<String> settingNamesSelected) {
for (String settingName : settingNamesSelected) {
if (settingName.equals(getResources().getString(R.string.api_setting_draw_line)))
mApiSettings.mDrawLine = true;
if (settingName.equals(getResources().getString(R.string.api_setting_search)))
mApiSettings.mLogSearch = true;
/* omitted rest of options for brevity */
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApiSettings = new ApiSettings();
setContentView(R.layout.activity_settings);
settingsRecyclerView = findViewById(R.id.settingsRecyclerView);
settingsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
Button backButton = findViewById(R.id.settings_back_button);
Button saveButton = findViewById(R.id.settings_apply_button);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setApiSettings(getSettingNamesSelected());
Intent intent = new Intent();
intent.putExtra("apiSettings", new Gson().toJson(mApiSettings));
setResult(RESULT_OK, intent);
finish();
}
});
listOfUsableApis = /* omitted for brevity */
final SettingsAdapter settingsAdapter = new SettingsAdapter();
settingsRecyclerView.setAdapter(settingsAdapter);
// Handle selection of settings
selectedSettingTracker = new SelectionTracker.Builder<Long>(
"selectedSettingTrackerId",
settingsRecyclerView,
new StableIdKeyProvider(settingsRecyclerView),
new SettingsDetailsLookup(),
StorageStrategy.createLongStorage()
).
withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).
build();
}
private List<String> getSettingNamesSelected() {
Selection<Long> settingsSelection = selectedSettingTracker.getSelection();
Iterator<Long> settingSelectionIterator = settingsSelection.iterator();
List<String> settingNamesSelected = new ArrayList<>();
while (settingSelectionIterator.hasNext()) {
Long settingSelectionId = settingSelectionIterator.next();
String settingNameSelected = listOfUsableApis.get(settingSelectionId.intValue());
settingNamesSelected.add(settingNameSelected);
}
return settingNamesSelected;
}
public static class ApiSettings {
public boolean mDrawLine = false;
public boolean mWalkSimulator = false;
/* omitted most options for brevity */
public ApiSettings() {
}
}
private class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.SettingViewHolder> {
public SettingsAdapter() {
setHasStableIds(true);
}
#NonNull
#Override
public SettingViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
TextView textView = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.setting_list_item, parent, false);
SettingViewHolder settingViewHolder = new SettingViewHolder(textView);
return settingViewHolder;
}
#Override
public void onBindViewHolder(#NonNull SettingViewHolder holder, final int position) {
holder.textView.setText(listOfUsableApis.get(position));
holder.textView.setActivated(selectedSettingTracker.isSelected((long) position));
holder.position = position;
}
#Override
public int getItemCount() {
return listOfUsableApis.size();
}
#Override
public long getItemId(int position) {
return Long.valueOf(position);
}
public class SettingViewHolder extends RecyclerView.ViewHolder {
public int position;
public TextView textView;
public SettingViewHolder(TextView v) {
super(v);
textView = v;
}
}
}
private class SettingsDetailsLookup extends ItemDetailsLookup<Long> {
#Nullable
#Override
public ItemDetails<Long> getItemDetails(#NonNull MotionEvent event) {
View view = settingsRecyclerView.findChildViewUnder(event.getX(), event.getY());
if (view != null) {
final RecyclerView.ViewHolder viewHolder = settingsRecyclerView.getChildViewHolder(view);
if (viewHolder instanceof SettingsAdapter.SettingViewHolder) {
final SettingsAdapter.SettingViewHolder settingViewHolder = (SettingsAdapter.SettingViewHolder) viewHolder;
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return viewHolder.getAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return Long.valueOf(settingViewHolder.position);
}
};
}
}
return null;
}
}
}
Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#454545"
android:weightSum="100">
<Button
android:id="#+id/settings_back_button"
android:background="#454545"
android:drawableStart="#drawable/arrow_white"
android:drawableLeft="#drawable/arrow_white"
android:layout_gravity="start"
android:layout_width="#dimen/ll_mdu_10"
android:layout_height="#dimen/ll_mdu_10"
android:layout_weight="5"/>
<Space
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="90"
/>
<Button
android:id="#+id/settings_apply_button"
android:background="#454545"
android:drawableStart="#android:drawable/ic_menu_save"
android:drawableLeft="#android:drawable/ic_menu_save"
android:layout_gravity="end"
android:layout_width="#dimen/ll_mdu_10"
android:layout_height="#dimen/ll_mdu_10"
android:layout_weight="5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Long-press for first setting, then tap other settings for multiple selection"
app:layout_constraintBottom_toTopOf="#+id/settingsRecyclerView"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/settingsRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</LinearLayout>
</LinearLayout>
Layout setting_list_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/setting_list_item_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/setting_background"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:textAppearance="?android:attr/textAppearanceListItemSmall" />
Background drawable setting_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark" android:state_activated="true" />
<item android:drawable="#android:color/white" />
</selector>
References:
https://developer.android.com/guide/topics/ui/layout/recyclerview#select This documentation is hard to read. It needs an example.
https://proandroiddev.com/a-guide-to-recyclerview-selection-3ed9f2381504 Hard to read Kotlin example
https://www.youtube.com/watch?v=jdKUm8tGogw&feature=youtu.be&list=PLWz5rJ2EKKc9Gq6FEnSXClhYkWAStbwlC&t=980 Google IO intro to this feature (but in Kotlin)
https://medium.com/#Dalvin/android-recycler-view-with-multiple-item-selections-b2af90eb5825 Another Java example!

How to limit this swipe refresh if its only at top?

This is my code which I used to make my data fetched from my data base in form of a list.But it is refreshing at all time when scroll down after a scrolled up for an instant . I need to make the refresh avail only when it is at top.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.adapter.ConnectAdapter;
import com.shuan.Project.asyncTasks.GetHome;
import com.shuan.Project.asyncTasks.GetPost;
import com.shuan.Project.employer.PostViewActivity;
import com.shuan.Project.list.Sample;
import java.util.ArrayList;
import java.util.HashMap;
public class OffersFragment extends Fragment {
private ArrayList<Sample> list;
private ConnectAdapter adapter;
private ListView listView;
private HashMap<String, String> cData;
private Common mApp;
private Context mContext;
private ProgressBar progressBar;
private SwipeRefreshLayout swipe;
public OffersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext=getActivity();
mApp= (Common) mContext.getApplicationContext();
View view = inflater.inflate(R.layout.fragment_employer_home, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
listView = (ListView) view.findViewById(R.id.post);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
list = new ArrayList<Sample>();
new GetPost(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id,""),"all", swipe).execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
TextView txt1= (TextView) view.findViewById(R.id.frm_id);
Intent in=new Intent(getActivity(),PostViewActivity.class);
in.putExtra("jId",txt.getText().toString());
in.putExtra("frmId",txt1.getText().toString());
in.putExtra("apply","no");
startActivity(in);
}
});
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new GetHome(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id, ""), "all",swipe).execute();
}
});
return view;
}
}
my xml file
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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"
tools:context="com.shuan.Project.fragment.ConnectionFragment">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ListView
android:id="#+id/post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:visibility="gone" />
</RelativeLayout>
Change your xml layout so SwipeRefreshLayout only wrap a scrollable view (your case the ListView).
<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"
tools:context="com.shuan.Project.fragment.ConnectionFragment">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:visibility="gone" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.enhancedListView.EnhancedListView
android:id="#+id/listaNoticias"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="5dp" >
</com.enhancedListView.EnhancedListView>
</android.support.v4.widget.SwipeRefreshLayout>
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.principal, container, false);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(android.R.color.holo_green_dark,
android.R.color.holo_red_dark,
android.R.color.holo_blue_dark,
android.R.color.holo_orange_dark); (...)
#Override
public void onRefresh() {
new myTask().execute();
}
I found my own solution for the question above. We can solve the issue by change the above code like below.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.adapter.ConnectAdapter;
import com.shuan.Project.asyncTasks.GetHome;
import com.shuan.Project.asyncTasks.GetPost;
import com.shuan.Project.employer.PostViewActivity;
import com.shuan.Project.list.Sample;
import java.util.ArrayList;
import java.util.HashMap;
public class OffersFragment extends Fragment implements AbsListView.OnScrollListener {
private ArrayList<Sample> list;
private ConnectAdapter adapter;
private ListView listView;
private HashMap<String, String> cData;
private Common mApp;
private Context mContext;
private ProgressBar progressBar;
private SwipeRefreshLayout swipe;
private int preLast;
public OffersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext=getActivity();
mApp= (Common) mContext.getApplicationContext();
View view = inflater.inflate(R.layout.fragment_employer_home, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
listView = (ListView) view.findViewById(R.id.post);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
list = new ArrayList<Sample>();
new GetPost(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id,""),"all", swipe).execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
TextView txt1= (TextView) view.findViewById(R.id.frm_id);
Intent in=new Intent(getActivity(),PostViewActivity.class);
in.putExtra("jId",txt.getText().toString());
in.putExtra("frmId",txt1.getText().toString());
in.putExtra("apply","no");
startActivity(in);
}
});
listView.setOnScrollListener(this);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new GetHome(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id, ""), "all",swipe).execute();
}
});
return view;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (view.getId() == R.id.post) {
if (firstVisibleItem == 0) {
swipe.setEnabled(true);
int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (preLast != lastItem) {
preLast = lastItem;
//Toast.makeText(getActivity(), "In Last", Toast.LENGTH_SHORT).show();
}
}else{
}
} else {
swipe.setEnabled(false);
}
}
}
}
This is a bit old, but in 2019 this is the correct answer: you have to include RecyclerView inside of NestedScrollView in order for SwipeRefreshLayout to behave properly, like this:
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
add this lines of code
note : LinearLayoutManager should be define separately
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mSwipeRefreshLayout.setEnabled
(mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
}
});
findFirstCompletelyVisibleItemPosition() == 0 means at the top of recyclerview

ListView with Custom extended BaseAdapter not showing with SherlockFragment, need hints or suggestions

I am new to android programming and I seem to have come at a stand still for several days now. I am having trouble finding a solution to my problem and tried many different solutions without success. As the title suggests, my code runs successfully but the ListView does not show up on the selected Tabs. Any suggestions of tips would be helpful.
ItemGuide.Java ------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ItemGuide extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), LeatherTab.class, null);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), SilverTab.class, null);
}
}
LeatherTab.java --------------------------------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class LeatherTab extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leather_fragment, container, false); //Fragment Layout inflated
TextView text = (TextView) view.findViewById(R.id.boxtest);//TextView for layout testing
text.setText("Hello");
ListView leather_listview = (ListView) view.findViewById(R.id.leather_list); // List is initialized
leather_listview.setAdapter(new LeatherAdapter(getActivity())); //Custom list adapter passes Context
return view;
}
}
LeatherAdapter.java ------------------------------------------------------
package com.example.alzuni_project;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class LeatherAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
public LeatherAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.leather_list_titles);
String[] descriptions = res.getStringArray(R.array.leather_list_description);
int[] images = {R.drawable.belt, R.drawable.wallet, R.drawable.coincase};
for (int i=0;i<images.length;i++) //Was originally 3
{
new SingleRow(titles[i], descriptions[i], images[i]);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.leather_title);
TextView description = (TextView) row.findViewById(R.id.leather_description);
ImageView image = (ImageView) row.findViewById(R.id.leather_icon);
SingleRow temp = list.get(position);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;//returns the rootView of single_row.xml
}
}
leatherfragment.xml ------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/boxtest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#CCDDFF" />
<ListView
android:id="#+id/leather_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/boxtest" />
</RelativeLayout>
SingleRow.java -----------------------------------------------------
package com.example.alzuni_project;
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title=title;
this.description=description;
this.image=image;
}
}
single_row.xml ---------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/leather_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="48dp"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/leather_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#CCCCCC" />
<TextView
android:id="#+id/leather_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/leather_icon"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_below="#+id/leather_title"
android:background="#CCDDFF" />
Your list seems empty , try this in your LeatherAdapter:
list.add(new SingleRow(titles[i],descriptions[i], images[i]));
Inside the for loop .

Categories