DoYouKnow Энциклопедия/Урок 12

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.neco_desarrollo.doyouknow.adapter.DataAdapter;
import com.neco_desarrollo.doyouknow.adapter.ListItem;
import com.neco_desarrollo.doyouknow.adapter.RecOnClickListener;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements NavItemSelectedListener {
private RecOnClickListener recOnClickListener;
private DataAdapter adapter;
private List<ListItem> listData;
private RecyclerView rcView;
private String category = "";
private SharedPreferences pref;
private final String PLANETS = "planets";
private final String STARS = "stars";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupMenu();
setRecOnClickListener();
init();



}
private void setupMenu() {
FragmentManager fm = getSupportFragmentManager();
MenuFragmentList mMenuFragment = (MenuFragmentList) fm.findFragmentById(R.id.id_container_menu);
if (mMenuFragment == null) {
mMenuFragment = new MenuFragmentList();
mMenuFragment.setNavItemSelectedListener(this);
fm.beginTransaction().add(R.id.id_container_menu, mMenuFragment).commit();
}
}


@Override
public void onNavItemSelectedListener(MenuItem item)
{
//Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId())
{
case R.id.id_favorite:
updateFav();
break;
case R.id.id_planets:

updateMainList(getResources().getStringArray(R.array.planets), PLANETS );
break;
case R.id.id_stars:
updateMainList(getResources().getStringArray(R.array.stars), STARS );
break;
case R.id.id_travel:

break;
case R.id.id_universal:

break;
case R.id.id_smart:

break;
case R.id.id_filosof:

break;
case R.id.id_umor:

break;
case R.id.id_ufo:

break;
case R.id.id_spirits:

break;

}
}

private void updateMainList(String[] array,String cat)
{
category = cat;
StringBuilder stringBuilder;
stringBuilder = new StringBuilder();
String tempCat = pref.getString(cat,"none");
if(tempCat != null)
{
if(tempCat.equals("none"))
{
for(int i = 0; i < array.length; i++)
{
stringBuilder.append("0");
}
Log.d("MyLog",cat + " " + stringBuilder.toString());
saveString(stringBuilder.toString());
}
else
{

}
}
List<ListItem> list = new ArrayList<>();
for(int i = 0; i < array.length; i++)
{
ListItem item = new ListItem();
item.setText(array[i]);
item.setCat(cat);
item.setPosition(i);
list.add(item);
}

adapter.updateList(list, false);
}
private void updateFav() {

List<ListItem> listFav = new ArrayList<>();
List<String[]> listData = new ArrayList<>();
listData.add(getResources().getStringArray(R.array.planets));
listData.add(getResources().getStringArray(R.array.stars));
String[] cat_array = {PLANETS, STARS};


for (int i = 0; i < listData.size(); i++)
{

for(int p = 0; p < listData.get(i).length; p++)
{
String d = pref.getString(cat_array[i],"none");
if(d != null)if(d.charAt(p) == '1')
{
ListItem item = new ListItem();
item.setText(listData.get(i)[p]);
item.setPosition(p);
item.setCat(cat_array[i]);
listFav.add(item);
}


}
}
adapter.updateList(listFav, true);

}
private void init()
{
pref = getSharedPreferences("CAT",MODE_PRIVATE);
rcView = findViewById(R.id.rcView);
rcView.setLayoutManager(new LinearLayoutManager(this));
listData = new ArrayList<>();
String[] planetsArray = getResources().getStringArray(R.array.planets);
adapter = new DataAdapter(this,recOnClickListener,listData);
updateMainList(planetsArray,"planets");
rcView.setAdapter(adapter);
}
private void setRecOnClickListener()
{
recOnClickListener = new RecOnClickListener()
{
@Override
public void onItemClicked(int pos)
{
//Toast.makeText(MainActivity.this, "Position = " + pos, Toast.LENGTH_SHORT).show();
String tempCat = pref.getString(category,"none");
if(tempCat != null)
{
if(tempCat.charAt(pos) == '0')
{
saveString(replaceCharAtPosition(pos,'1',tempCat));
}
else
{
saveString(replaceCharAtPosition(pos,'0',tempCat));
}
}

}
};
}
private String replaceCharAtPosition(int position, char ch, String st)
{
char[] charArray = st.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
private void saveString(String stToSave)
{
SharedPreferences.Editor editor = pref.edit();
editor.putString(category,stToSave);
editor.apply();
Log.d("MyLog","Saved data fav : " + pref.getString(category,"none"));
}

}

MenuFragmentList.java

import android.graphics.Typeface;
import android.os.Bundle;

import android.text.Spannable;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.navigation.NavigationView;

/**
* Created by mxn on 2016/12/13.
* MenuListFragment
*/

public class MenuFragmentList extends Fragment {
private NavItemSelectedListener navItemSelectedListener;



@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container,
false);

NavigationView vNavigation = view.findViewById(R.id.vNavigation);
vNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
//Toast.makeText(getActivity(), menuItem.getTitle(), Toast.LENGTH_SHORT).show();
navItemSelectedListener.onNavItemSelectedListener(menuItem);

return false;
}
});

Menu m = vNavigation.getMenu();
for (int i=0;i<m.size();i++) {
MenuItem mi = m.getItem(i);

//for aapplying a font to subMenu ...
SubMenu subMenu = mi.getSubMenu();
if (subMenu!=null && subMenu.size() > 0 ) {
for (int j=0; j <subMenu.size();j++) {
MenuItem subMenuItem = subMenu.getItem(j);
applyFontToMenuItem(subMenuItem);
}
}

//the method we have create in activity
applyFontToMenuItem(mi);
}



return view;
}

private void applyFontToMenuItem(MenuItem mi) {
if (getActivity() != null) {
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), getString(R.string.font2));
SpannableString mNewTitle = new SpannableString(mi.getTitle());
mNewTitle.setSpan(new CustomTypeFaceSpan("", font), 0, mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mi.setTitle(mNewTitle);
}
}

public void setNavItemSelectedListener(NavItemSelectedListener navItemSelectedListener) {
this.navItemSelectedListener = navItemSelectedListener;
}
}

CustomTypeFaceSpan.java

import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;

public class CustomTypeFaceSpan extends TypefaceSpan {

private final Typeface newType;

public CustomTypeFaceSpan(String family, Typeface type) {
super(family);
newType = type;
}

@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}

@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}

private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}

int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}

if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}

paint.setTypeface(tf);
}
}

NavItemSelectedListener.java

import android.view.MenuItem;

public interface NavItemSelectedListener {
void onNavItemSelectedListener(MenuItem item);
}

DataAdapter.java

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.neco_desarrollo.doyouknow.R;

import java.util.List;

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.DataHolder> {

private Context context;
private RecOnClickListener recOnClickListener;
private List<ListItem> listItemArray;
private SharedPreferences pref;
private boolean isFav;


public DataAdapter(Context context, RecOnClickListener recOnClickListener, List<ListItem> listItemArray) {
this.context = context;
this.recOnClickListener = recOnClickListener;
this.listItemArray = listItemArray;
pref = context.getSharedPreferences("CAT",Context.MODE_PRIVATE);

}

@NonNull
@Override
public DataHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout,parent,false);
return new DataHolder(view);
}

@Override
public void onBindViewHolder(@NonNull DataHolder holder, int position) {
holder.setData(listItemArray.get(position));
}

@Override
public int getItemCount() {
return listItemArray.size();
}

public class DataHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private boolean isFavChecked = false;
private TextView tvText;
private ImageButton imButFav;

public DataHolder(@NonNull View itemView)
{
super(itemView);
tvText = itemView.findViewById(R.id.tvText);
imButFav = itemView.findViewById(R.id.imBut);
imButFav.setOnClickListener(this);
}
public void setData(ListItem item)
{
tvText.setText(item.getText());
if(!isFav){
setFav(item, getAdapterPosition());
}
else
{
setFavAll();
}
}


@Override
public void onClick(View v)
{
isFavChecked = !isFavChecked;
if(isFavChecked)
{
imButFav.setImageResource(android.R.drawable.btn_star_big_on);
}
else
{
imButFav.setImageResource(android.R.drawable.btn_star_big_off);
}
if(!isFav){
recOnClickListener.onItemClicked(getAdapterPosition());
}
else
{
deleteItem();
}
}
private String replaceCharAtPosition(int position, char ch, String st)
{
char[] charArray = st.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
private void saveString(String stToSave)
{
ListItem item = listItemArray.get(getAdapterPosition());
SharedPreferences.Editor editor = pref.edit();
editor.putString(item.getCat(),stToSave);
editor.apply();
//Log.d("MyLog","Saved data fav : " + pref.getString(category,"none"));
}
private void deleteItem()
{
ListItem item = listItemArray.get(getAdapterPosition());
String dataToChange = pref.getString(item.getCat(),"none");
if(dataToChange == null)return;
String replacedData = replaceCharAtPosition(item.getPosition(),'0', dataToChange);
saveString(replacedData);
listItemArray.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(), listItemArray.size());

}
private void setFavAll(){
imButFav.setImageResource(android.R.drawable.btn_star_big_on);
}
private void setFav(ListItem item, int position)
{
String fav_data = pref.getString(item.getCat(),"none");

if(fav_data != null)
{
char[] charArray = fav_data.toCharArray();
switch (charArray[position])
{
case '0':
imButFav.setImageResource(android.R.drawable.btn_star_big_off);
isFavChecked = false;
break;
case '1':
imButFav.setImageResource(android.R.drawable.btn_star_big_on);
isFavChecked = true;
break;
}

}

}
}


public void updateList(List<ListItem> listArray, boolean isFav)
{
this.isFav = isFav;
listItemArray.clear();
listItemArray.addAll(listArray);
notifyDataSetChanged();
}
}

ListItem.java

public class ListItem {
private String text;
private String cat;
private int position;

public int getPosition() {
return position;
}

public void setPosition(int position) {
this.position = position;
}

public String getCat() {
return cat;
}

public void setCat(String cat) {
this.cat = cat;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}
}

RecOnClickListener.java

public interface RecOnClickListener {
void onItemClicked(int pos);
}

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *