I followed this tutorial on youtube for my school project. The app is able to display selected images from gallery but the recycler view have gaps in every row. What do I code to fix this app? help. enter image description here
here's my activity_main.xml
<?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"
android:orientation="vertical"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/pick"
android:layout_width="53dp"
android:layout_height="64dp"
android:layout_margin="12dp"
android:layout_weight="0"
android:backgroundTint="#FF5722"
android:text="+"
android:textSize="24sp"
app:cornerRadius="64dp" />
<TextView
android:id="#+id/totalPhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:textColor="#FFFFFF" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_Gallery_Images"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
</LinearLayout>
RecyclerAdapter.java
package com.example.mygram;
import android.media.Image;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Uri> uriArrayList;
public RecyclerAdapter(ArrayList<Uri> uriArrayList) {
this.uriArrayList = uriArrayList;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.custom_single_image,parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(uriArrayList.get(position));
}
#Override
public int getItemCount() {
return uriArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
}
}
}
Custom single images.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
And here's the MainActivity.java
package com.example.mygram;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView textView;
Button pick;
ArrayList <Uri> uri = new ArrayList<>();
RecyclerAdapter adapter ;
private static final int Read_Permission = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.totalPhotos);
recyclerView = findViewById(R.id.recyclerView_Gallery_Images);
pick = findViewById(R.id.pick);
adapter = new RecyclerAdapter(uri);
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
recyclerView.setAdapter(adapter);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Read_Permission);
}
pick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
if(data.getClipData() !=null) {
int x = data.getClipData().getItemCount();
for (int i = 0; i < x; i++) {
uri.add(data.getClipData().getItemAt(i).getUri());
}
adapter.notifyDataSetChanged();
textView.setText("Photos ("+uri.size()+")");
}else if (data.getData()!=null){
String imageURL=data.getData().getPath();
uri.add(Uri.parse(imageURL));
}
}
}
}
The concept of the app is instagram feed tester. I want to be able to display images like the grid in instagram but the gap is appearing preventing it to happen. help me please thankyou
In your Custom single images.xml replace the height of the parent layout to wrap_content. Replace your code with the following
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Everything is right : Just need to Change this to this: (images.xml)
android:layout_height="match_parent"
to
android:layout_height="wrap_content"
in your model xml file
Related
I'm trying to have a button appear only on the last page of a ViewPager. I have the working button but it is displayed on all the pages instead of only the last page. I want to have it visible only on the last page. Here is my code.
activity_welcome2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".Welcome_Activity"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--- for dots -->
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#+id/dotsLayout"
android:background="#color/white"
android:layout_marginBottom="15dp" />
<LinearLayout
android:id="#+id/dotsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="55sp" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/next3"
android:layout_width="99dp"
android:layout_height="45dp"
android:background="#android:color/transparent"
android:scaleType="fitCenter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.822"
app:srcCompat="#drawable/next" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Welcome_Activity.java
package com.group7.salitongue;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
public class Welcome_Activity extends AppCompatActivity {
private ViewPager mPager;
private int[] layouts = { R.layout.activity_main, R.layout.activity_splashscreen2, R.layout.activity_welcome };
private MpagerAdapter mpagerAdapter;
private LinearLayout Dots_Layout;
private ImageView[] dots;
private ImageButton nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome2);
mPager = (ViewPager) findViewById(R.id.viewPager);
mpagerAdapter = new MpagerAdapter(layouts, this);
mPager.setAdapter(mpagerAdapter);
Dots_Layout = (LinearLayout) findViewById(R.id.dotsLayout);
createDots(0);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
createDots(position);
}
#Override
public void onPageScrollStateChanged(int state) {}
});
// transition button to Signup page
nextBtn = (ImageButton) findViewById(R.id.next3);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Welcome_Activity.this,MainActivity.class);
startActivity(intent);
}
});
}
private void createDots(int current_position) {
if(Dots_Layout != null)
Dots_Layout.removeAllViews();
dots = new ImageView[layouts.length];
for (int i = 0; i < layouts.length; i++) {
dots[i] = new ImageView(this);
if (i == current_position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots));
}
else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.default_dots));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
Dots_Layout.addView(dots[i],params);
}
}
}
How can I display the button only when the user has reached the last page of swiping?
Just listen in the onPageSelected method of your OnPageChangeListener when the last page is reached and set the button to visible. In all other cases, just hide it.
#Override
public void onPageSelected(int position) {
createDots(position);
// only show the button when the last page is reached
if (position == mPagerAdapter.getCount() - 1)
nextBtn.setVisibility(View.VISIBLE);
else
nextBtn.setVisibility(View.GONE);
}
I am using youtube API top import youtube channel in android app. I have created MainActivity, Adapter, Video Datails Class and another activity named youtubePlay activity. the xml for main activity consists of list view and another custom layout with text and image for list view items display obtained from json parsing (title, description, thumbnail). I have added youtube player view in the activity_play_youtube. but on clicking the video from list, the video is not displayed on the youtube player view.
the coding is as shown;
MainActivity.java
package com.currentmedia.channel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.currentmedia.channel.Adapter.MyCustomAdapter;
import com.currentmedia.channel.Model.VideoDetails;
import static android.widget.Toast.*;
public class MainActivity extends AppCompatActivity {
//private static final String TAG = "Channel Activity";
String API_Key = "[]";
ListView listView;
ArrayList<VideoDetails> videoDetailsArrayList;
MyCustomAdapter myCustomAdapter;
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCVMWWQ985A_-SESZUy_SsVQ&maxResults=50&key=[]";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
videoDetailsArrayList = new ArrayList<>();
myCustomAdapter = new MyCustomAdapter(MainActivity.this, videoDetailsArrayList);
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")){
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault=jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id=jsonVideoId.getString("videoId");
VideoDetails vd=new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsArrayList.add(vd);
}
listView.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(), LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
}
the adapter class named myCustomAdapter is following
package com.currentmedia.channel.Adapter;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.currentmedia.channel.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import com.currentmedia.channel.Model.VideoDetails;
public class MyCustomAdapter extends BaseAdapter {
Activity activity;
ArrayList<VideoDetails> videoDetailsArrayList;
LayoutInflater inflater;
public MyCustomAdapter(Activity activity, ArrayList<VideoDetails> videoDetailsArrayList)
{
this.activity=activity;
this.videoDetailsArrayList=videoDetailsArrayList;
}
#Override
public Object getItem(int position) {
return this.videoDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return (long) position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater==null)
{inflater=this.activity.getLayoutInflater();}
if(convertView == null)
{convertView=inflater.inflate(R.layout.custom_layout,null);}
ImageView imageView=(ImageView) convertView.findViewById(R.id.imageView);
TextView textView=(TextView) convertView.findViewById(R.id.mytitle);
LinearLayout linearLayout=(LinearLayout)convertView.findViewById(R.id.root);
final VideoDetails videoDetails=(VideoDetails) this.videoDetailsArrayList.get(position);
linearLayout.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(activity, com.currentmedia.channel.VideoPlayActivity.class);
i.putExtra("videoId", videoDetails.getVideoId());
activity.startActivity(i);}
});
Picasso.get().load(videoDetails.getUrl()).into(imageView);
textView.setText(videoDetails.getTitle());
return convertView;
}
#Override
public int getCount() {
return this.videoDetailsArrayList.size();
}
}
videoPlayActivity.java
package com.currentmedia.channel;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubePlayerView;
public class VideoPlayActivity extends YouTubeBaseActivity {
YouTubePlayerView youTubePlayerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_play);
youTubePlayerView= (YouTubePlayerView) findViewById(R.id.youtube_player) ;
}
}
and the xml files are :
activity_video_play
<?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=".VideoPlayActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/youtube_player"></com.google.android.youtube.player.YouTubePlayerView>
</RelativeLayout>
while activity_main and custom_layout is as follows
<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"></ListView>
</RelativeLayout>
<?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="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:orientation="horizontal"
android:id="#+id/root">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:id="#+id/mytitle"
android:text="welcome to my video"
android:textSize="16sp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
can anybody explain where am I doing wrong?
In your videoPlayActivity.java
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
String url = getIntent().getStringExtra("videoId");
youTubePlayerView = findViewById(R.id.youtube_player);
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(url);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
youTubePlayerView.initialize("Api key", onInitializedListener);
To generate Api key https://developers.google.com/youtube/android/player/register
Just got many problems sorted out on my bottom navigation bar, but now the app crashes whenever I click on any of the 3 navigation bar Icons.
Error
2020-07-23 15:41:26.397 25876-25876/com.example.sociate11 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sociate11, PID: 25876
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:245)
at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:180)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:343)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:293)
at com.example.sociate11.activityHome$2.onNavigationItemSelected(activityHome.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:124)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
activityHome.java
package com.example.sociate11;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class activityHome extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogOut);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(activityHome.this, MainActivity.class));
}
});
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home_fragment:
selectedFragment = new HomeFragment();
break;
case R.id.events_fragment:
selectedFragment = new EventFragment();
break;
case R.id.fragment_myconversation:
selectedFragment = new ConversationFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
ConversationsFragment.java (all 3 fragments are currently identical)
package com.example.sociate11;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ConversationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_myconversations,container,false);
}
}
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_home"
android:title="Home"
android:icon="#drawable/ic_home"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myEvents"
android:title="My Events"
android:icon="#drawable/ic_event"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myConversations"
android:title="My Conversations"
android:icon="#drawable/ic_conversations"
app:showAsAction="always"/>
</menu>
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".activityHome"
android:background="#color/colorPrimary">
<Button
android:id="#+id/btnLogOut"
android:layout_width="115dp"
android:layout_height="75dp"
android:text="log out"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation_bar" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemTextColor="#color/colorPrimaryDark"
app:itemIconTint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogOut"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you for the help as always, and please let me know if I didn't provide enough info!
I want to add a spinner to my app to change the language of strings in an array list but not sure how to do so.
I made a sample app to try to change and tried couple of things but they didn't work. I know it's a basic thing but I really have no idea how to do it.
Here is the code for XML layout file
<android.support.constraint.ConstraintLayout 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">
<Spinner
android:id="#+id/language_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/list_item"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/list_item"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/list_item"
android:layout_width="368dp"
android:layout_height="352dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginBottom="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
For the main activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner languageSpinner = (Spinner) findViewById(R.id.language_spinner);
final ListView list = (ListView) findViewById(R.id.list_item);
/*Creating an ArrayAdapter that is populated with languagelist to populate the languageSpinner*/
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.language_list, android.R.layout.simple_dropdown_item_1line);
/*Populating the languageSpinner with the spinnerAdapter*/
languageSpinner.setAdapter(spinnerAdapter);
languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
Toast.makeText(getApplicationContext(), "Language changed to " + (CharSequence) languageSpinner.getSelectedItem() , Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView arg0) {
Toast.makeText(getApplicationContext(), "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this ,android.R.layout.simple_list_item_1, arrayList ) ;
list.setAdapter(arrayAdapter);
}
}
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
configuration.setLocale(Locale.forLanguageTag("fa"));
resources.updateConfiguration(configuration, displayMetrics);
finish();
startActivity(getIntent());
First of all you have to build a new string file in a new values folder in your resource folder for example i want to add persian in my app and build a value file with the name of values-fa and copy your string.xml file to it
and change the string to the language you want .
and then you have to add this code to your spinner OnItemSelectedListener(). This work for me.
MyEventsFragment.java
List item
package com.example.edvenswa.collabevents;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class MyEventsFragment extends FragmentActivity{
ViewPager viewPager = null;
MyAdapter myAdapter;
public MyEventsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_my_events);
viewPager = (ViewPager) findViewById(R.id.myEventsPager);
/*List<Fragment> listFragments = new ArrayList<Fragment>();
listFragments.add(new MyEventsInsideFragment());
listFragments.add(new ExpiredEventsFragment());
listFragments.add(new AttendingEventsFragment());
listFragments.add(new PastAttendingEventsFragment());*/
myAdapter = new MyAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.myEventsPager);
viewPager.setAdapter(myAdapter);
}
/* #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my_events, container, false);
}*/
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Log.d("count","count called"+i);
Fragment fragment = null;
if (i == 0) {
fragment = new MyEventsInsideFragment();
}
if (i == 1) {
fragment = new ExpiredEventsFragment();
}
if (i == 2) {
fragment = new AttendingEventsFragment();
}
if (i == 3) {
fragment = new PastAttendingEventsFragment();
}
return fragment;
}
#Override
public int getCount() {
Log.d("count", "count called");
return 4;
}
}
fragment_my_events.xml
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.edvenswa.collabevents.MyEvents">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/myEventsPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:gravity="center">
</android.support.v4.view.ViewPager>
</FrameLayout>
So, this is my code. here I am able to view the first page in fragment but unable scroll and no view of other fragments.
Note: This MyEventsFragment.java is also a fragment in the sidedrawer.
First add the design support library if you haven't
compile 'com.android.support:design:23.0.0'
then add the TabLayout like this one.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
Then in your onCreate() method below the viewPager add the following line,
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
Also, in your FragmentPageAdapter, you'll have to override getPageTitle() method for returning your Tabs title.