I'm having an issue with my app when I inflate an recyclerview.
Inside the recyclerview, some cards are inflated and when it comes out to the screen, the toolbar disappears and the settings button can't be used.
Using the latest SDK and libraries versions.
activity_main.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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
linha.xml -> here I get the cardview which I use to show the items on the recyclerview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="#style/CardView.Light"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<TextView
android:id="#+id/titulo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textColor="#000000"
tools:text="Titulo Noticia"
app:layout_constraintEnd_toStartOf="#+id/imagem"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/dataPublicacao"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#8A000000"
tools:text="18 Setembro 2020"
app:layout_constraintEnd_toStartOf="#+id/imagem"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/titulo" />
<ImageView
android:id="#+id/imagem"
android:layout_width="140dp"
android:layout_height="140dp"
android:layout_margin="12dp"
tools:background="#color/colorAccent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/url"
android:layout_width="0dp"
android:layout_height="0dp"
android:visibility="invisible"
tools:ignore="MissingConstraints"
app:layout_constraintTop_toBottomOf="#+id/dataPublicacao" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
MainActivity.java
package br.ufpe.cin.android.rss;
import androidx.appcompat.app.AppCompatActivity;
package br.ufpe.cin.android.rss;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.prof.rssparser.Article;
import com.prof.rssparser.Channel;
import com.prof.rssparser.OnTaskCompleted;
import com.prof.rssparser.Parser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String urlFeed;
private Toolbar mTopToolbar;
RecyclerView conteudoRSS;
List<Article> noticias;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conteudoRSS = findViewById(R.id.conteudoRSS);
mTopToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mTopToolbar);
SharedPreferences preferences = getSharedPreferences
("user_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("feed1", getString(R.string.feed1));
editor.putString("feed2", getString(R.string.feed2));
editor.putString("feed3", getString(R.string.feed3));
editor.apply();
if(preferences.contains("rssfeed")){
urlFeed = preferences.getString("rssfeed", getString(R.string.feed_padrao));
} else {
editor.putString("rssfeed", getString(R.string.feed_padrao));
editor.apply();
urlFeed = preferences.getString("rssfeed", getString(R.string.feed_padrao));
}
conteudoRSS = new RecyclerView(this);
conteudoRSS.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(
this, PreferenciasActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
Parser p = new Parser.Builder().build();
p.onFinish(
new OnTaskCompleted() {
#Override
public void onTaskCompleted(Channel channel) {
noticias = channel.getArticles();
runOnUiThread(
() -> {
RssAdapter adapter = new RssAdapter(
getApplicationContext(),
noticias
);
conteudoRSS.setAdapter(adapter);
setContentView(conteudoRSS);
}
);
}
#Override
public void onError(Exception e) {
Log.e("RSS_APP",e.getMessage());
}
}
);
p.execute(urlFeed);
}
protected void onResume() {
super.onResume();
}
private String getRssFeed(String feed) throws IOException {
InputStream in = null;
String rssFeed;
try {
URL url = new URL(feed);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
rssFeed = new String(response, StandardCharsets.UTF_8);
} finally {
if (in != null) {
in.close();
}
}
return rssFeed;
}
}
conteudoRSS = new RecyclerView(this);
conteudoRSS.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(
this, PreferenciasActivity.class));
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
Parser p = new Parser.Builder().build();
p.onFinish(
new OnTaskCompleted() {
#Override
public void onTaskCompleted(Channel channel) {
noticias = channel.getArticles();
runOnUiThread(
() -> {
RssAdapter adapter = new RssAdapter(
getApplicationContext(),
noticias
);
conteudoRSS.setAdapter(adapter);
setContentView(conteudoRSS);
}
);
}
#Override
public void onError(Exception e) {
Log.e("RSS_APP",e.getMessage());
}
}
);
p.execute(urlFeed);
}
protected void onResume() {
super.onResume();
}
private String getRssFeed(String feed) throws IOException {
InputStream in = null;
String rssFeed;
try {
URL url = new URL(feed);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1; ) {
out.write(buffer, 0, count);
}
byte[] response = out.toByteArray();
rssFeed = new String(response, StandardCharsets.UTF_8);
} finally {
if (in != null) {
in.close();
}
}
return rssFeed;
}
}
ItemRssViewHolder.java
package br.ufpe.cin.android.rss;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
public class ItemRssViewHolder extends RecyclerView.ViewHolder {
TextView titulo = null;
ImageView image = null;
TextView data = null;
TextView url = null;
public ItemRssViewHolder(View itemCard) {
super(itemCard);
this.titulo = itemCard.findViewById(R.id.titulo);
this.image = itemCard.findViewById(R.id.imagem);
this.data = itemCard.findViewById(R.id.dataPublicacao);
this.url = itemCard.findViewById(R.id.url);
itemCard.setOnClickListener(
v -> {
String uri = url.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemCard.getContext().startActivity(intent);
}
);
}
}
RssAdapter.java
package br.ufpe.cin.android.rss;
import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.prof.rssparser.Article;
import com.squareup.picasso.Picasso;
import java.util.List;
import static br.ufpe.cin.android.rss.R.layout.linha;
public class RssAdapter extends RecyclerView.Adapter <ItemRssViewHolder> {
List<Article> noticias;
Context context;
public RssAdapter(Context c, List<Article> noticias) {
this.noticias = noticias;
this.context = c;
}
public int getCount() {
return noticias.size();
}
public Object getItem(int i) {
return noticias.get(i);
}
#NonNull
#Override
public ItemRssViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.linha, parent, false);
ItemRssViewHolder viewHolder = new ItemRssViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ItemRssViewHolder viewHolder, int i) {
Article noticia = noticias.get(i);
viewHolder.titulo.setText(noticia.getTitle());
viewHolder.data.setText("Publicado em: " + noticia.getPubDate().substring(0, 22));
viewHolder.url.setText(noticia.getLink());
String url = noticias.get(i).getImage();
Picasso.with(context)
.load(url)
.into(viewHolder.image);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getItemCount() {
return noticias.size();
}
}
Because you align the top of Recyclerview to the top of parent (ConstraintLayout) so it overs the toolbar.
Replace app:layout_constraintTop_toTopOf="parent" with app:layout_constraintTop_toBottomOf="#id/toolbar" to align the top of Recyclerview to the bottom of Toolbar
Add these attrs to your Toolbar:
app:layout_constraintBottom_toTopOf="#id/conteudoRSS"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
<?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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#id/conteudoRSS"
tools:ignore="MissingConstraints">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/toolbar"/> <!-- replace app:layout_constraintTop_toTopOf="parent" -->
</androidx.constraintlayout.widget.ConstraintLayout>
LinearLayout is also good, it's simpler than ConstraintLayout in this case
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
Try this
<?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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#id/conteudoRSS"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:layout_constraintStart_toStartOf="parent">
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/conteudoRSS"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/toolbar" /><!--TODO:Edit-->
</androidx.constraintlayout.widget.ConstraintLayout>
If this does not work, try adding android:layout_marginTop="?attr/actionBarSize" to RecyclerView.
Hope this helps. Feel free to ask for clarifications...
Issue fixed with the help of Vishnu, who's answered this question.
It seems the problem was that I was creating a new recycleview on the main activity instead of using the recycleview defined by the layout xml file.
To fix that, it was only necessary to remove two lines from the main activity:
conteudoRSS = new RecyclerView(this);
setContentView(conteudoRSS);
And maintain only the first definition of the recycleview, as follows:
RecyclerView conteudoRSS;
conteudoRSS = findViewById(R.id.conteudoRSS);
Related
I am facing the problem of cannot see widgets in tab layouts. I have created textview and button in Overview Fragment but I cannot see them when run code. Is it right to initialize textviews and buttons in oncreateview() of fragment which we don't want to transfer to another tab. I have searched a lot about my problem but cannot get any hint. Code is given below:
package com.example.progluattempt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
public class GlucosePlotterTips extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glucose_plotter_tips);
TabLayout Tablayout1 = findViewById(R.id.Tablayout1);
TabItem OverviewTab = findViewById(R.id.Overviewtab);
TabItem HistoryTab = findViewById(R.id.Historytab);
TabItem TipsTab = findViewById(R.id.Tipstab);
ViewPager Viewpager1 = findViewById(R.id.viewpagery1);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), Tablayout1.getTabCount());
Viewpager1.setAdapter(pagerAdapter);
Tablayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Viewpager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
//PgeAdapter
package com.example.progluattempt;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
private int numoftabs;
public PagerAdapter(FragmentManager fm, int numoftabs){
super(fm);
this.numoftabs = numoftabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new OverviewFragment();
case 1:
return new HistoryFragment();
case 2:
return new TipsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numoftabs;
}
}
//Main.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=".GlucosePlotterTips">
<com.google.android.material.tabs.TabLayout
android:id="#+id/Tablayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004">
<com.google.android.material.tabs.TabItem
android:id="#+id/Overviewtab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overview" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Historytab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="History" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Tipstab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tips" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpagery1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
//fragmentOverview
<FrameLayout 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=".OverviewFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="183dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewov2"
android:layout_width="match_parent"
android:layout_height="56dp"
android:text="#string/overview1"
android:textColor="#color/black"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewov3"
android:layout_width="match_parent"
android:layout_height="46dp"
android:text="TextView"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
<Button
android:id="#+id/buttonov2"
android:layout_width="277dp"
android:layout_height="93dp"
android:layout_gravity="center"
android:text="#string/planner"
android:textColor="#color/black"
android:textSize="24sp"
app:backgroundTint="#color/Yellow" />
//OverviewFragment
package com.example.progluattempt;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
TextView Results, Condition;
Button Mybuttonov2;
public OverviewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
Results = (TextView) view.findViewById(R.id.textViewov2);
Intent i =getActivity().getIntent();
String LatestReading=i.getStringExtra("TimeofReading");
Results.setText("Last Checked: " +LatestReading);
//type
Condition = (TextView) view.findViewById(R.id.textViewov3);
String TypeofDiab = i.getStringExtra("Concentration");
Condition.setText("" +TypeofDiab);
//Button
Mybuttonov2 = (Button) view.findViewById(R.id.buttonov2);
//to display conditon of user
if(Condition.getText() != null){
String num;
int numi=0;
num = Condition.getText().toString();
try{
numi = Integer.parseInt(num);
}catch(NumberFormatException ex){
}
if(numi <= 70){
System.out.println("Hypoglycemia");}
else if(numi >=70 & numi <= 140){
System.out.println("Fine");}
else if(numi>140 & numi <200){
System.out.println("Prediabetes");}
else {
System.out.println("Hyperglycemia");
}
}
//to add click event for button
Mybuttonov2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i3 = new Intent(getActivity(), SensorScreen.class );
startActivity(i3);
}
});
return view;
}
}
Logcat
When run emulator
I wanna have same fab transformation behavior as shown in
Material Website in Full Screen (or morph) section.
I have tried default FabTransformationScrimBehavior and FabTransformationSheetBehavior. but scrim behavior doesn't do anything and sheet behavior don't animate just like I wanted and also it reduce the elevation of the fab to value 0f. and I haven't found any way to unexpand fab. and I wanna know how to use fab transformation behavior. Actually I didn't find any doc on how to use it. So Please help
Code
This is the code that I used:
this is the code of first activity:-
final FloatingActionButton actionButton = findViewById(R.id.add_fab);
actionButton.setOnClickListener(view -> {
actionButton.setExpanded(!actionButton.isExpanded());
});
And this is the xml of first activity:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/include_generic_toolbar" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingBottom="76dp"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
tools:listitem="#layout/media_list_item_card" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/add_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:includeFontPadding="false"
android:text="Add Media"
android:textAllCaps="false"
android:visibility="visible"
app:srcCompat="#drawable/ic_add_24"/>
<com.google.android.material.circularreveal.CircularRevealFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
app:layout_behavior="com.google.android.material.transformation.FabTransformationSheetBehavior"
>
<fragment
android:id="#+id/fab_transformation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.zimong.ssms.fragments.AddMediaFragment"
/>
</com.google.android.material.circularreveal.CircularRevealFrameLayout>
And the code of AddMediaFragment(second screen):-
package com.zimong.ssms.fragments;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.zimong.ssms.R;
import com.zimong.ssms.common.model.User;
import com.zimong.ssms.extended.CallbackHandlerImpl;
import com.zimong.ssms.model.Source;
import com.zimong.ssms.model.ZResponse;
import com.zimong.ssms.service.AppService;
import com.zimong.ssms.service.ServiceLoader;
import com.zimong.ssms.util.Constants;
import com.zimong.ssms.util.Util;
import java.util.Calendar;
import java.util.Date;
import retrofit2.Call;
import retrofit2.Response;
public class AddMediaFragment extends DialogFragment {
private ArrayAdapter<Source> adapter;
private TextView source;
private int checkedItem = 0;
private TextView mediaDate;
private Date currentSelectedDate;
public static AddMediaFragment newInstance() {
AddMediaFragment fragment = new AddMediaFragment();
Bundle bundle = new Bundle();
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme_Light);
setHasOptionsMenu(true);
}
private void getSources() {
final User user = Util.getUser(getActivity());
AppService service = ServiceLoader.createService(AppService.class);
Call<ZResponse> call = service.mediaGallerySources(Constants.DEFAULT_PLATFORM, user.getToken());
call.enqueue(new CallbackHandlerImpl<Source[]>(getActivity(), true, true, Source[].class) {
#Override
protected void failure(Throwable t) {
}
#Override
protected void failure(Response<ZResponse> response) {
}
#Override
protected void success(Source[] response) {
if (response.length > 0) {
source.setText(response[0].getName());
}
adapter = new ArrayAdapter<Source>(getContext(), R.layout.dialog_singlechoice_item, response) {
#Override
public long getItemId(int position) {
return getItem(position).getPk();
}
};
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_add_media, container, false);
TextView headline = view.findViewById(R.id.media_headline);
Toolbar toolbar = view.findViewById(R.id.toolbar);
((AppCompatActivity) getContext()).setSupportActionBar(toolbar);
source = view.findViewById(R.id.source);
mediaDate = view.findViewById(R.id.media_date);
Calendar fromDateInstance = Calendar.getInstance();
currentSelectedDate = fromDateInstance.getTime();
mediaDate.setText(Util.formatDate(fromDateInstance.getTime(), "dd MMM yyyy"));
final DatePickerDialog fromDatePicker = new DatePickerDialog(getContext(), (datePicker, year, month, date) -> {
fromDateInstance.set(Calendar.YEAR, year);
fromDateInstance.set(Calendar.MONTH, month);
fromDateInstance.set(Calendar.DATE, date);
currentSelectedDate = fromDateInstance.getTime();
mediaDate.setText(Util.formatDate(currentSelectedDate, "dd MMM yyyy"));
}, fromDateInstance.get(Calendar.YEAR), fromDateInstance.get(Calendar.MONTH), fromDateInstance.get(Calendar.DATE));
mediaDate.setOnClickListener(v -> fromDatePicker.show());
source.setOnClickListener(v -> alertDialog());
getSources();
return view;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void alertDialog() {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(getContext());
builder.setTitle("Source");
builder.setSingleChoiceItems(adapter, checkedItem, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
source.setText(adapter.getItem(which).getName());
checkedItem = which;
dialog.dismiss();
}
});
builder.show();
}
}
And the xml of Add Media is:-
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.circularreveal.coordinatorlayout.CircularRevealCoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/myCoordinatorLayout"
android:layout_width="match_parent"
android:background="#color/white"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$Behavior"
android:theme="#style/AppTheme.AppBarOverlay">
<include layout="#layout/include_toolbar" />
</com.google.android.material.appbar.AppBarLayout>
<include
layout="#layout/content_add_media"
android:layout_width="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
android:layout_height="match_parent"/>
</com.google.android.material.circularreveal.coordinatorlayout.CircularRevealCoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">
<com.google.android.material.circularreveal.CircularRevealLinearLayout
android:id="#+id/dial"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_gravity="bottom|center_horizontal"
android:visibility="invisible"
android:layout_marginBottom="16dp"
app:layout_anchor="#id/fab"
app:layout_anchorGravity="top|center_horizontal"
android:background="#color/colorPrimary"
app:layout_behavior="com.google.android.material.transformation.FabTransformationSheetBehavior">
<ImageButton
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/back"/>
</com.google.android.material.circularreveal.CircularRevealLinearLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:backgroundTint="#color/colorPrimary"
app:srcCompat="#android:drawable/ic_dialog_email"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
For the FabTransformationSheetBehavior to work, you need to change the isExpanded value.
on change of this value, expand and collapse animation will be called and visibility of the linearlayout and fab button will be handled automatically. Don't change visibility manually as this would block transformation animation.
Use back button to transform back to FAB.
val fab: FloatingActionButton = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener { fab.isExpanded = !fab.isExpanded } // this sets isExpanded as true
val back = findViewById<ImageButton>(R.id.back)
back.setOnClickListener{ fab.isExpanded = !fab.isExpanded } // this sets isExpanded as false
I am working on an Android app with Tab navigation. I have three tabs and I would like to display separate informations on each tab. On the first tab, I would like to display a list of items that are retrieved from an SQlite database. The items are entered through dialogs, which is working well. I keep the logic for the collection and display of data in the Main Activity:
package com.example.TodoList;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.app.AlertDialog;
import android.widget.SimpleCursorAdapter;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.TodoList.db.TaskContract;
import com.example.TodoList.db.TaskDBHelper;
import com.example.TodoList.fragments.ThreeFragment;
import com.example.TodoList.fragments.TwoFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListAdapter listAdapter;
private TaskDBHelper helper;
private Button btnIconTextTabs;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_favourite,
R.drawable.ic_tab_call,
R.drawable.ic_tab_contacts
};
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
//ListView listView = (ListView) findViewById(R.id.list);
//listView.setAdapter(listAdapter);
updateUI();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnIconTextTabs = (Button) findViewById(R.id.btnIconTextTabs);
//btnIconTextTabs.setOnClickListener(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
adapter.addFrag(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText inputField = new EditText(this);
builder.setNegativeButton("Cancel", null);
switch (item.getItemId()) {
case R.id.action_add_task:
builder.setTitle("Add an article to your shopping list");
builder.setMessage("What would you like to add?");
builder.setView(inputField);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK, task);
db.insertWithOnConflict(TaskContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
builder.create().show();
return true;
case R.id.action_remove_task:
builder.setTitle("Remove an article from the shopping list");
builder.setMessage("Did you found this article?");
builder.setNegativeButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
updateUI();
}
});
case R.id.action_show_mylocation:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
//Intent intent=new Intent(this,LbsGeocodingActivity.class);
//startActivity(intent);
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
MainActivity.this.startActivity(GeoLocationIntent);
}
builder.create().show();
return true;
}
private void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
}
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
public void onSubmitPriceClick(View view) {
Intent SubmitPriceIntent = new Intent(MainActivity.this, SubmitPriceActivity.class);
MainActivity.this.startActivity(SubmitPriceIntent);
}
public void onWebViewButtonClick(View view) {
Intent intent = new
Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.batprice.com:1337"));
startActivity(intent);
finish();
}
public void onGeoLocationButtonClick(View view) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
MainActivity.this.startActivity(GeoLocationIntent);
}
/*#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnIconTextTabs:
startActivity(new Intent(MainActivity.this, IconTextTabsActivity.class));
break;
}
}*/
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
This is my First fragment, where I want to display the list items:
package com.example.TodoList.fragments;
import android.content.Context;
import android.database.SQLException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.TodoList.R;
import java.util.ArrayList;
public class OneFragment extends FragmentActivity {
public OneFragment() {
// Required empty public constructor
}
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(OneFragment.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
return inflater.inflate(R.layout.fragment_one, container, false);
}
/*
public static class OneFragment extends Fragment {
ListView list;
list = (ListView) view.findViewById(R.id.listview);
DataDB data = new DataDB();
ArrayAdapter<String> listAdapter;
public ListDoctorFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.listdoctor, container, false);
ArrayList<String> names = new ArrayList<String>();
try {
names = data.getDoctorlistDB(getActivity());
} catch (SQLException e) {
e.printStackTrace();
}
listAdapter = new ArrayAdapter<String>(getActivity(), R.layout.support_simple_spinner_dropdown_item, names);
// set the adapter
list.setAdapter(listAdapter);
return view;
}
}
*/
}
This is the activity icon text tabs layout file:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
This is my main activity layout file:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_margin="5dp" />
<Button
android:id="#+id/btnIconTextTabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/btn_icon_text_tabs"
android:textSize="15dp" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
This is my main layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_margin="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onGeoLocationButtonClick"
android:text="Your Location" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onSubmitPriceClick"
android:text="Submit a price" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onScrollViewButtonClick"
android:text="Scrollview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onWebViewButtonClick"
android:text="Webview" />
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is my Fragment one layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_margin="5dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onGeoLocationButtonClick"
android:text="Your Location" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onSubmitPriceClick"
android:text="Submit a price" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onScrollViewButtonClick"
android:text="Scrollview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="clip_vertical"
android:onClick="onWebViewButtonClick"
android:text="Webview" />
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
I would like to display the entered list items - this whole processus is working well - in fragment One, but the list items are not showing up. I don´t get any errors so I´m a bit stuck here. Any help or hints would be very appreciated, thanks.
I'm trying to create a list of Card view using a custom adapter. I have defined the layout of a single row of list, consisting a card view and imageview/textviews in it, in a separate .xml file. I'm using a custom srrsy adapter. My app crashes when I try to open the activity having list view , giving only an Runtime-exception error.
Error:
AndroidRuntime(2583): at graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter.getView(PostArrayAdapter.java:44)
This error is at the line
LayoutInflater li =(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
in custom adapter.
Here is single_card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/ll1">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="#+id/ll2">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:id="#+id/imgIcon"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll3"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SampleTitle1"
android:layout_marginTop="10dp"
android:background="#00b5ad"
android:textSize="20dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/title"
android:textColor="#ffffff"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sampledisription1"
android:layout_marginTop="10dp"
android:background="#ffffff"
android:textSize="10dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/desciption"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Here is PostArrayAdapter.java
package graph.prathya.com.nextstepz.CustomAdapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import graph.prathya.com.nextstepz.R;
/**
* Created by Prathya on 5/23/2015.
*/
public class PostArrayAdapter extends ArrayAdapter<Post>{
Context context;
Post data[] =null;
int layoutid;
public PostArrayAdapter(Context context, int layoutid, Post data[]) {
super(context,layoutid);
this.data=data;
this.layoutid=layoutid;
}
private class PostHolder{
ImageView imgIcon;
TextView title,description;
}
#Override
public int getCount(){
return data.length;
}
#Override
public View getView(int Position, View convertView, ViewGroup parent){
PostHolder holder;
View v = convertView;
if(v==null){
LayoutInflater li = LayoutInflater.from(context);/* RunTimeExceptio error at this line of code */
v= li.inflate(layoutid,parent,false);
holder = new PostHolder();
holder.imgIcon = (ImageView)v.findViewById(R.id.imgIcon);
holder.title = (TextView)v.findViewById(R.id.title);
holder.description= (TextView)v.findViewById(R.id.desciption);
v.setTag(holder);
}
else {
holder = (PostHolder)v.getTag();
}
Post post = data[Position];
holder.imgIcon.setImageResource(post.imgIcon);
holder.title.setText(post.title);
holder.description.setText(post.description);
return v;
}
}
Here is activity in which listView lies: HomeScreenAvtivity.java
package graph.prathya.com.nextstepz;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import graph.prathya.com.nextstepz.Communicator.Communicater1;
import graph.prathya.com.nextstepz.CustomAdapters.Post;
import graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter;
public class HomeScreenActivity extends ActionBarActivity {
ImageButton passionbtn, eventbtn, projectbtn, groupstudybtn;
Dialog dg;
ListView listView = null;
Post post[] =new Post[] {
new Post(R.drawable.img1,"Cats and Children","Cats can be a fascinating experience for children, but young minds can sometimes confuse a pet for a toy. Teach children how to respect and properly handle your cat for best results."),
new Post(R.drawable.img2,"Android:The Best OS","Android powers hundreds of millions of mobile devices in more than 190 countries around the world.Android’s openness has made it a favorite for consumers."),
new Post(R.drawable.img3,"Beautiful","Monica is an Italian actor and model who started her modelling career at the age of 13 by posing for a local photo enthusiast."),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView)findViewById(R.id.homelist);
listView.setAdapter(new PostArrayAdapter(getApplicationContext(),R.layout.single_card_view,post));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == R.id.nxtsignupitem) {
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.eventitem1) {
Intent in = new Intent(getApplicationContext(), PostDetailActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.postitem11) {
dg = new Dialog(HomeScreenActivity.this);
dg.requestWindowFeature(Window.FEATURE_NO_TITLE);
dg.setContentView(R.layout.fragment_new_post_dialogue);
dg.setTitle("Please choose One option");
dg.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dg.show();
passionbtn = (ImageButton) dg.findViewById(R.id.imageButton1st);
eventbtn = (ImageButton) dg.findViewById(R.id.imageButton2);
projectbtn = (ImageButton) dg.findViewById(R.id.imageButton3);
groupstudybtn = (ImageButton) dg.findViewById(R.id.imageButton4);
passionbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(1);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
eventbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(2);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
projectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(3);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
groupstudybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(4);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
}
return super.onOptionsItemSelected(item);}
#Override
public boolean onCreateOptionsMenu(Menu menu){
// TODO Auto-generated method stub
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_home_screen, menu);
return super.onCreateOptionsMenu(menu);
} }
XML layout file of HomeScreenActivity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/lord"
android:layout_marginBottom="20dp"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/homelist">
</ListView>
</LinearLayout>
</ScrollView>
Post.java used in Adapter
package graph.prathya.com.nextstepz.CustomAdapters;
/**
* Created by Prathya on 5/23/2015.
*/
public class Post {
int imgIcon;
String title,description;
public Post(int imgIcon,String title, String description){
this.imgIcon=imgIcon;
this.title=title;
this.description=description;
}
}
you never assign context in your constructor.
add
this.context = context;
to your constructor
My Android listview does not update with notifydatasetchanged() call.
The Main Code Activity:
package com.example.jokesbook;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.jokesbook.MESSAGE";
CustomAdapter Adapter;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JokeDB.jokesList = new ArrayList<Joke>();
JokeDB.jokesList.add(new Joke("DDD"));
lv = (ListView)findViewById(android.R.id.list);
Adapter= new CustomAdapter(MainActivity.this, R.layout.joke_list_item, JokeDB.jokesList);
lv.setAdapter(Adapter);
}//onCreate
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Log.d("jokesbook", "onResume ");
Adapter.notifyDataSetChanged();
}
class CustomAdapter extends ArrayAdapter<Joke>{
Context context;
int layoutResourceId;
ArrayList<Joke> data = null;
private LayoutInflater mInflater;
public CustomAdapter(Context customAdapter, int layoutResourceId, ArrayList<Joke> data) {
super(customAdapter, layoutResourceId, data);
Log.d("jokesbook", "CustomAdapter ");
this.layoutResourceId = layoutResourceId;
this.context = customAdapter;
this.data = data;
this.mInflater = LayoutInflater.from(customAdapter);
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
//item_list
convertView = mInflater.inflate(R.layout.joke_list_item, null);
holder = new ViewHolder();
//fill the views
holder.joke = (TextView) convertView.findViewById(R.id.ListTextView1);
convertView.setTag(holder);
}
else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();//
}
holder.joke.setText(data.get(position).jokeStr);
return convertView;
}
class ViewHolder {
TextView joke;
}
}
/** Called when the user clicks the Add a new joke button */
public void goNewJoke(View view) {
Intent intent = new Intent(this, New_joke.class);
startActivity(intent);
}
}
Its xml:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/ButtonAboveList"
android:layout_width="500dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:onClick="goNewJoke"
android:text="#string/Add_a_new_joke"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
When adding content to JokeDB.jokesList in another activity that its code is:
package com.example.jokesbook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class New_joke extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_joke);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_joke, menu);
return true;
}
public void addJoke(View view){
EditText editTextJoke= (EditText)findViewById(R.id.edit_text_jokeToAdd);
JokeDB.jokesList.add(new Joke(editTextJoke.getText().toString()));
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
and its XML is:
<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:background="#color/green"
android:orientation="vertical"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="3dp"
tools:context=".New_joke" >
<EditText
android:id="#+id/edit_text_jokeToAdd"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginBottom="40dp"
android:background="#color/white"
android:hint="#string/edit_message" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
tools:context=".New_joke" >
<TextView
android:id="#+id/AuthorText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/Author"
android:textColor="#android:color/white"
android:textSize="25sp" />
<EditText
android:id="#+id/edit_text_Author"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#color/white"
android:hint="#string/Only_letters_allowed"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="60dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
tools:context=".New_joke" >
<TextView
android:id="#+id/DateText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/Date"
android:textColor="#android:color/white"
android:textSize="25sp" />
<EditText
android:id="#+id/edit_text_Date"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#color/white"
android:hint="#string/Only_digits_allowed"
android:inputType="number" />
</LinearLayout>
<Button
android:id="#+id/ButtonAboveList"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addJoke"
android:text="#string/Add" />
</LinearLayout>
I cannot see the updated list in the main activity eveb though in onResume I used notifydatasetchanged() function.
Try This....
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Log.d("jokesbook", "onResume ");
notifyDataSetChanged();
}